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
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
If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,
However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:
Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:
References:
To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:
=>
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 remember that you need to escape your seperators using single quotes.
The following will return the string represention you wanted:
This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.
Another way is:
which gives you 2008-09-22T14:01:54.9571247Z
To get the specified format, you can use:
DateTime Formatting Options