考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
当前回答
System.DateTime.UtcNow.ToString("o")
=>
val it : string = "2013-10-13T13:03:50.2950037Z"
其他回答
DateTime.UtcNow.ToString("s")
返回类似2008-04-10T06:30:00的内容
UtcNow显然返回UTC时间,所以在以下情况下没有伤害:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
像2018-06-22T13:04:16这样的格式可以在API的URI中传递:
public static string FormatDateTime(DateTime dateTime)
{
return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}
读者注意:一些评论指出了这个答案中的一些问题(特别是与第一个建议有关)。更多信息请参考评论部分。
DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz", CultureInfo.InvariantCulture);
使用自定义日期-时间格式,这将为您提供类似于 2008 - 09 - 22 - t13:57:31.2311892内。
另一种方法是:
DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
它使用标准的“往返”风格(ISO 8601)来给你 2008 - 09 - 22 - t14:01:54.9571247z。
要获得指定的格式,您可以使用:
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)
DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");
DateTime.Now.ToString("O");
注意:根据您在终端所做的转换,您将使用第一行(最接近它)或第二行。
确保只在本地时间应用格式,因为“zzz”是UTC转换的时区信息。
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