1

i have a big problem with a DateTime-Format after deserializing a json-string to a Dataset.

Dim formatter = new JsonSerializerSettings() With { .DateFormatString = "yyyy-MM-ddThh:mm:ssZ" }
Dim json = JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented,formatter)

After this two lines I get a well formed DateTime-Format (e.g. "2015-11-24T09:36:00Z")

But after that, I have to convert this json-string to a DataSet-Object. I do it like this:

Dim ds = JsonConvert.DeserializeObject(Of DataSet)(json,formatter)

And now, the DateTime-Value looks like this: "11/24/2015 09:36:00"

Finally this value ends in an Exception, that it is not a valide DateTime, if I want do parse it to an DateTime...

DateTime.Parse("11/24/2015 09:36:00")

So maybe there are some formatters which i have to use? I don't know...

Hope you can help me! Thank you in advance!

EDIT: Sample-Jsonstring:

{"records":[{"Key":"EIG*11111","ChangeDate":"2015-11-24T09:36:00Z"}]}

This ChangeDate will be formatted to #11/24/2015 09:36:00 AM# in the DataRow

  • 1
    Try `DateTime.ParseExact` with a format string instead. – Ron Beyer Apr 04 '18 at 18:24
  • 1
    `DateTime.Parse` is culture-specific and relies on localization. Check if your computer format is MM/DD/YYY and not DD/MM/YYYY – Miro J. Apr 04 '18 at 18:28
  • 1
    Can you please [edit] your question to share sample JSON that reproduces the problem -- i.e. a [mcve]? – dbc Apr 04 '18 at 22:02

1 Answers1

0

JSON.NET has IsoDateTimeConverter class where you can specify date format to parse formatted UTC datetime in JSON string as DateTime with DateTimeFormat property. The property usage should be like this:

Dim formatter As New IsoDateTimeConverter With { .DateTimeFormat = "dd/MM/yyyy" }
Dim ds = JsonConvert.DeserializeObject(Of DataSet)(json, formatter)

Or use it in one-line form:

Dim ds = JsonConvert.DeserializeObject(Of DataSet)(json, New IsoDateTimeConverter With { .DateTimeFormat = "dd/MM/yyyy" })

Note that you need adding Newtonsoft.Json.Converters namespace to enable IsoDateTimeConverter class.

Afterwards, use DateTime.ParseExact() with specified format above to make sure that returned date string can be converted to DateTime type.

Similar issue (in C# context):

Deserializing dates with dd/mm/yyyy format using Json.Net

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61