Given a DateTime object, how do I get an ISO 8601 date in string format?

Given:

DateTime.UtcNow

How do I get a string which represents the same value in an ISO 8601-compliant format?

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz");

This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00 .

Another way is:

DateTime.UtcNow.ToString("o");

which gives you 2008-09-22T14:01:54.9571247Z

To get the specified format, you can use:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")

DateTime Formatting Options


DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.


DateTime.UtcNow.ToString("s")

Returns something like 2008-04-10T06:30:00

UtcNow obviously returns a UTC time so there is no harm in:

string.Concat(DateTime.UtcNow.ToString("s"), "Z")
链接地址: http://www.djcxy.com/p/5984.html

上一篇: 如何解析ISO 8601

下一篇: 给定一个DateTime对象,如何获得字符串格式的ISO 8601日期?