13

I got a bunch of DateTime-Strings I want to parse into a c# DateTime.

2009-06-18 02:10:31.296761+00
2009-06-18 02:13:34.049145+00
2009-01-06 23:52:21.510121+00
2009-06-18 02:17:57.268252+00
2010-01-22 03:31:26.512496+00
2009-06-18 01:32:37.930961+00

I'm currently trying to get the DateTime-Object with the following line of code:

DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.None);

But I'm always getting a System.FormatException.

2
  • 9
    That's not ISO 8601 compliant inputs Commented Oct 17, 2013 at 7:48
  • 4
    As commented by Shaw, that is not strictly ISO 8601 format. The standard requires a T in the middle rather than a SPACE. For example, 2009-06-18T02:10:31.296761+00. A SPACE is optionally allowed only on special arrangement by both parties of the data exchange, sender and recipient. Commented Sep 15, 2016 at 15:59

1 Answer 1

21

You don't have to do anything fancy, a simple DateTime.Parse works:

DateTime myDate1 = DateTime.Parse("2009-06-18 02:10:31.296761+00");
DateTime myDate2 = DateTime.Parse("2009-06-18 02:10:31.296761+03");

Both lines will work and the resulting dates will take the offset into account.

The reason this works is that the format you supplied is one of the standard datetime formats, specifically the universal sortable format, not ISO 8601.

ISO 8601 corresponds to the roundtrip format and uses 'T' instead of ' ' to separate date from time.

Sign up to request clarification or add additional context in comments.

1 Comment

I experienced errors when parsing an ISO8601 date with the roundtrip format ('O'). The roundtrip format seems to require a fully specified date and time, including fractional seconds (e.g. 2006-05-04T00:00:00.0000000),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.