5

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kaya
  • 515
  • 2
  • 7
  • 19
  • 4
    ISO 8601 also allows a time zone offset to be specified (eg "2009-10-08T12:52:02+04:30" would be the same time as above). However none of the answers address this... – Peter McEvoy Apr 11 '12 at 08:49

2 Answers2

18
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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
JDunkerley
  • 12,355
  • 5
  • 41
  • 45
6

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • 3
    Cheers but the wiki shows both formats – Kaya Oct 08 '09 at 09:24
  • 2
    I was unable to parse my string using either "u" or "s" however replacing the T with a space is easily done. This seems to work. I'm using VB .NET with .NET 2.0. – Brian Sweeney Sep 23 '10 at 16:51
  • @romkyns Answer seems correct for me. From your "ISO-8601 standard" doc I read in chapters 3.4.3 and 4.3.2 that the "T" is needed when date and time is shown. See also examples B.1.3. And dates in format as presented in question are handled natively. – StefanG May 05 '16 at 09:29
  • @StefanG Hm yeah, the only thing I can find in the spec is that "T" can be omitted _by mutual agreement_, which is not the same as a space being a valid separator. I've deleted my comment. – Roman Starkov May 20 '16 at 12:49