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
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
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")
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.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
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)