tags:

views:

9034

answers:

4

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: (Wikipedia). The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

+6  A: 

DateTime.UtcNow.ToString("s")

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

UtcNow obviously returns a Utc time so no harm in:

string.Concat(DateTime.UtcNow.ToString("s"), "Z")

Iain
Just out of interest: Why string.Concat() rather than '+'?
Daniel Fortunov
Habbit, is there a difference?
Iain
+37  A: 

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 format you specified in your Edit, you can use:

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

DateTime Formatting Options

Wayne
+9  A: 

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

Simon Wilson
I believe this is the correct answer. There is no point in explicitly defining the yyyy-MM-etc if Microsoft already implemented ISO 8601. Iain's response was right, too, but you should always specify the InvariantCulture (or any other CultureInfo) for multiple reasons (i.e. never assume .NET should just assume). You can also use:`DateTime.UtcNow.ToString(CultureInfo.InvariantCulture.DateTimeFormat.SortableDateTimePattern);`However, since all of these exclude the time zone, etc., you might have no choice but to use the explicit formatter, i.e. `"yyyy-MM-ddTHH:mm:ss.fffZ"`
stimpy77
+1  A: 

To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remeber that you need to escape your seperators using single quotes.

The following will return the string represention you wanted:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
Oppositional