考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
当前回答
The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
-来自MSDN
其他回答
DateTime.UtcNow.ToString("s")
返回类似2008-04-10T06:30:00的内容
UtcNow显然返回UTC时间,所以在以下情况下没有伤害:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
如果你在SharePoint 2010或更高版本下开发,你可以使用
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
...
string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)
您有一些选项,包括“往返(“O”)格式说明符”。
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("O"));
Console.WriteLine(date1.ToString("s", System.Globalization.CultureInfo.InvariantCulture));
输出
2008-03-01T07:00:00.0000000
2008-03-01T07:00:00
然而,DateTime + TimeZone可能会出现其他问题,如博客文章DateTime和DateTimeOffset in .NET:良好实践和常见陷阱中所述:
DateTime有无数的陷阱,旨在给你的代码错误: 1.- DateTime值与DateTimeKind。不确定是坏消息。 2.- DateTime在比较时不关心UTC/Local。 3.- DateTime值不支持标准格式字符串。 4.—解析带DateTime的UTC标记的字符串不能保证UTC时间。
System.DateTime.UtcNow.ToString("o")
=>
val it : string = "2013-10-13T13:03:50.2950037Z"
DateTime.UtcNow。ToString("s", System.Globalization.CultureInfo.InvariantCulture)应该给你你想要的,因为"s"格式说明符被描述为一个可排序的日期/时间模式;符合ISO 8601标准。
编辑:为了得到OP要求的额外Z,使用“o”而不是“s”。