Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse C# DateTime

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.

like image 538
Daniel M Avatar asked Oct 17 '13 07:10

Daniel M


1 Answers

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.

like image 84
Panagiotis Kanavos Avatar answered Oct 02 '22 13:10

Panagiotis Kanavos