Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem deserializating JSON Date in C# - adding 2 hours

We are having such a nasty problem when deserializating a JSON date to a C# DateTime.

The code is:

JavaScriptSerializer serializer = new JavaScriptSerializer();
jsonTrechos = jsonTrechos.Replace("/Date(", "\\/Date(").Replace(")/", ")\\/");
Trecho[] model = serializer.Deserialize<Trecho[]>(jsonTrechos);

The jsonTrechos is a string of json2.js's JSON.stringify();.

Problem is: the deserialization works, bur all dates of the Trechos objects are added with 2 hours.

My timezone is Brazil (UTC -3) and we're under daylight savings (so we're currently on UTC -2), if it has anything to do. I guess that perhaps localization and timezones may be playing a part on this and if they really are, I have no idea on how to fix it.

like image 406
viniciushana Avatar asked Nov 29 '10 14:11

viniciushana


Video Answer


2 Answers

This is documented in the MSDN:

Date object, represented in JSON as "/Date(number of ticks)/". The number of ticks is a positive or negative long value that indicates the number of ticks (milliseconds) that have elapsed since midnight 01 January, 1970 UTC.

Try calling DateTime.ToLocalTime() and see if you get the correct date for you.

like image 111
Razzie Avatar answered Sep 19 '22 23:09

Razzie


I would strongly recommend working with the Json.NET library. Quite frankly, the JSON serializers (and there are multiple ones) in the .NET framework are all quirky in some way, especially when it comes to serializing dates.

Json.NET is the only library that I've seen that handles them (and JSON in general) consistently and without problem for other consumers.

like image 44
casperOne Avatar answered Sep 20 '22 23:09

casperOne