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
Returns something like 2008-04-10T06:30:00
UtcNow
obviously returns a UTC time so there is no harm in:I would just use
XmlConvert
:It will automatically preserve the time zone.
You can get the "Z" (ISO 8601 UTC) with the next code:
Here is why:
The ISO 8601 have some different formats:
DateTimeKind.Local
DateTimeKind.Utc
DateTimeKind.Unspecified
.NET provides us with an enum with those options:
Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.
Source: Standard Date and Time Format Strings (MSDN)
– from MSDN
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.It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.
Also it is interesting that "S" format is slow on Classic and fast on Core...
Of course numbers are very close, between some rows difference is insignificant (tests with suffix
_Verify
are the same as those that are without that suffix, demonstrates results repeatability)Code:
https://github.com/dotnet/BenchmarkDotNet was used