Parse ISO 8601 to C# DateTime

Daniel M picture Daniel M · Oct 17, 2013 · Viewed 22.5k times · Source

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.

Answer

Panagiotis Kanavos picture Panagiotis Kanavos · Oct 17, 2013

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.