.net DateTime Serialization Deserialization bug

If you serialize and deserialize a DateTime using embedded .net JavaScriptSerializer, you get two different dates if you are in UTC+something !

Example (suppose you are in UTC+2 like I am now)

JavaScriptSerializer myJson = new JavaScriptSerializer();

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 14:12:00 ! WRONG! IT's in UTC+0 ! Has 2 HOURS less !!!

So, when you get the deserialized date, it'll give you the UTC+0 value by default...!!

This is different from JavaScriptSerializer UTC DateTime issues because that article describes the difference in deserialization of different datetime data types, and provides a solution (.UtcDateTime) that doesn't fix the problem. In fact, trying to deserialize with .utcDateTime a serialized DateTime always gives you the wrong UTC+0 date...


There are two different solutions: either use ToLocalTime() when you deserialize OR use the Newtonsoft.Json.

So the same code, "fixed", in the first case should be:

JavaScriptSerializer myJson = new JavaScriptSerializer();

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized).ToLocalTime();

Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 16:12:00 !!! CORRECT !

Otherwise, using Newtonsoft.Json (you first need to install it from nuGet, then add a "using Newtonsoft.Json" at the top), and use it like this:

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = JsonConvert.SerializeObject(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = JsonConvert.DeserializeObject<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//NO need to convert to LocalTime... it already gives you 2016-03-29 16:12:00 !!! CORRECT !

I hope this will be useful for someone else... I googled a lot and found nothing about this problem that only happens with Microsoft serializer...

链接地址: http://www.djcxy.com/p/46642.html

上一篇: 如何增加邮件大小配额

下一篇: .net DateTime序列化反序列化错误