使用ISO 8601日期格式添加两秒
问题描述:
我正面临有关ISO 8601格式日期时间操作的问题。问题是,我有一个日期字符串这样使用ISO 8601日期格式添加两秒
string date = "2014-09-05T23:39:57-04:00";
我需要额外2秒添加到这个日期。
但是,当我尝试使用DateTime.Parse
方法将此字符串转换为添加2秒时,DateTime.Parse
方法正在将日期更改为“9/6/2014 9:09:57 AM”。但我需要这样的结果
string calculateddate = "2014-09-05T23:39:59-04:00";
如何实现这一目标?
感谢 Utpal Maity
答
试试这个:
// you start with this string - it contains a time-zone information
string date = "2014-09-05T23:39:57-04:00";
// this is a DateTimeOffset - and this doesn't have any format - it's a binary blob of 8 bytes
DateTimeOffset yourDate = DateTimeOffset.Parse(date);
// add two seconds to it - this is still an 8 byte binary blob ....
DateTimeOffset twoSecondsAdded = yourDate.AddSeconds(2);
// display it in the format you want
string output = twoSecondsAdded.ToString("yyyy-MM-ddTHH:mm:ss K");
Console.WriteLine("Date with 2 seconds added: {0}", output);
,你应该得到的输出:
Date with 2 seconds added: 2014-09-05T23:39:59 -04:00
,了解这一点很重要
-
因为你
- 有在你的日期字符串时区符时,必须使用
DateTimeOffset
- 一个
DateTimeOffset
(或DateTime
)在.NET中仅有8个字节的二进制 - 它不具有任何格式 - 可以显示
DateTimeOffset
,无论如何你像 - 只需使用适当的.ToString()
覆盖来指定格式