Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize ISO 8601 date time string to C# DateTime

Tags:

c#

json.net

I'm trying to use:

JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )

But it gives me a FormatException: Input string was not in a correct format.

What am I doing wrong?

like image 432
Dirk Boer Avatar asked Jun 25 '13 15:06

Dirk Boer


1 Answers

If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:

DateTime value = DateTime.ParseExact(text, "o", null);

The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

I haven't specified a format provider, as it doesn't matter:

The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.

If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.

Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.

like image 131
Jon Skeet Avatar answered Sep 28 '22 20:09

Jon Skeet