JSON Date deserialization issue in C # - adding 2 hours

We have such an unpleasant problem when the deserialization of a JSON date dates from C # DateTime.

Code:

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

jsonTrechos is a string json2.js JSON.stringify(); .

The problem is that deserialization works, and all dates of Trechos objects are added after 2 hours.

My time zone is Brazil (UTC -3), and we are under summer savings (so we are currently in UTC -2) if this is done. I suggest that perhaps localization and time zones can play a role in this, and if they really are, I have no idea how to fix this.

+4
source share
4 answers

This is described on MSDN :

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

Try calling DateTime.ToLocalTime() see if you entered the date correctly.

+11
source

I highly recommend working with the Json.NET library. Quite frankly, the JSON serializers (and several of them) in the .NET platform are all bizarre, especially when it comes to serializing dates.

Json.NET is the only library I've seen that processes them (and JSON in general) sequentially and without problems for other consumers.

+6
source

The dates indicated for JSON are UTC, and as you mentioned, you are using daylight saving, so +2 hours makes sense. Ideally, you should work with UTC time dates anyway, as it eliminates headaches in daylight (or in this case, it is added to it) and allows global hosting.

+2
source

"Javascript dates are calculated in milliseconds from January 01, 1970 00:00:00 UTC with a day containing 86,400,000 milliseconds." (Excerpt from W3schools). Therefore, you want to convert it to your time zone.

 TimeZoneInfo.ConvertTimeFromUtc(yourDateToConvert, TimeZoneInfo.Local) 
+1
source

All Articles