Parsing ISO 8601 dates in C#
Question:
How to convert an ISO 8601 format date string to a .NET DateTime object in C#?
For example, given the string "2010-08-20T15:00:00Z", how do you parse it into a DateTime object?
Answer:
Conversion can be accomplished using the DateTime.Parse
method, combined with the appropriate DateTimeStyles
options:
<code class="language-csharp">DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);</code>
RoundtripKind
style option ensures that the "Z" character in the string is correctly interpreted, identifying it as a UTC time.
The complete code example is as follows:
<code class="language-csharp">string iso8601String = "2010-08-20T15:00:00Z"; DateTime parsedDate = DateTime.Parse(iso8601String, null, System.Globalization.DateTimeStyles.RoundtripKind); Console.WriteLine(parsedDate); // 输出:2010/8/20 15:00:00</code>
The above is the detailed content of How to Parse ISO 8601 Dates in C#?. For more information, please follow other related articles on the PHP Chinese website!