Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ISO 8601 string to DateTime in .NET? [duplicate]

I have a string, "2009-10-08 08:22:02Z", which is in ISO 8601 format.

How do I use DateTime to parse this format?

like image 264
Kaya Avatar asked Oct 08 '09 09:10

Kaya


2 Answers

string txt= "2009-10-08 08:22:02Z";
DateTime output = DateTime.ParseExact(txt, "u", System.Globalization.CultureInfo.InvariantCulture);

The DateTime class supports the standard format string of u for this format

I think for the ISO format (with the T separator), use "s" instead of "u". Or use:

string txt= "2009-10-08 08:22:02Z";
DateTime output = DateTime.ParseExact(txt, new string[] {"s", "u"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

to support both formats.

like image 121
JDunkerley Avatar answered Nov 15 '22 11:11

JDunkerley


No, it's not ISO 8601. Valid ISO 8601 representation would have T between time and date parts.

DateTime can natively handle valid ISO 8601 formats. However, if you're stuck with this particular representation, you can try DateTime.ParseExact and supply a format string.

like image 24
Anton Gogolev Avatar answered Nov 15 '22 09:11

Anton Gogolev