考虑到:
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
其他回答
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
使用Newtonsoft。Json,你可以这样做
JsonConvert.SerializeObject(DateTime.UtcNow)
例如:https://dotnetfiddle.net/O2xFSl
DateTime.UtcNow.ToString("s")
返回类似2008-04-10T06:30:00的内容
UtcNow显然返回UTC时间,所以在以下情况下没有伤害:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");
DateTime.Now.ToString("O");
注意:根据您在终端所做的转换,您将使用第一行(最接近它)或第二行。
确保只在本地时间应用格式,因为“zzz”是UTC转换的时区信息。
DateTime.UtcNow。ToString("s", System.Globalization.CultureInfo.InvariantCulture)应该给你你想要的,因为"s"格式说明符被描述为一个可排序的日期/时间模式;符合ISO 8601标准。
编辑:为了得到OP要求的额外Z,使用“o”而不是“s”。