Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 206
Iain Avatar asked Sep 22 '08 13:09

Iain


People also ask

How do I format a date in ISO 8601?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

Should be a valid ISO 8601 date string?

Yes, it is valid. It's basically extended in terms of subsecond support, but that's allowed by the standard.


2 Answers

Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.

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

Using custom date-time formatting, this gives you a date similar to
2008-09-22T13:57:31.2311892-04:00.

Another way is:

DateTime.UtcNow.ToString("o"); 

which uses the standard "round-trip" style (ISO 8601) to give you
2008-09-22T14:01:54.9571247Z.

To get the specified format, you can use:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") 
like image 166
Wayne Avatar answered Sep 29 '22 18:09

Wayne


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.

EDIT: To get the additional Z at the end as the OP requires, use "o" instead of "s".

like image 37
Simon Wilson Avatar answered Sep 29 '22 18:09

Simon Wilson