Tuesday 10 May 2011

Serializing DateTime values using JavaScriptSerializer class

As you know .NET Framework's System.Web.Script.Serialization.JavaScriptSerializer class can be used to to do C# to JSON serialization and JSON to C# deserialization. When JavaScriptSerializer serializes a DateTime into a JSON string it uses the Local DatetimeKind, unless otherwise specified while creating the DateTime, resulting in a potential problem while deserializing it. The reason is AJAX framework deserializes DateTime value assuming its Kind property is set to Utc format. So if the serialized DateTime is created using a different DateTimeKind deserialization will produce a different DateTime value.

For example assume your Local is GMT+1 and you have serialized the DateTime value "15-May-2011 00:00:00" using JavaScriptSerializer and passed it to a WCF method where you deserialize it. Here deserialization will produce a DateTime with the value "14-May-2011 23:00:00". This is because deserialization assumes the value is serialized using Utc DateTimeKind, which is nothing but GMT time, and it uses the same DateTimeKind.Utc to deserialize it. So it results in a DaTime value which is one hour (remember the Local is GMT+1) less than the original value.

The fix is do something similar to below code snippet before serializing which will make sure DateTimeKind.Utc will be used for serializing the value.

DateTime departureDate = DateTime.SpecifyKind(value, DateTimeKind.Utc);

And finally you will get the correct value after deserialzation in the WCF method or wherever you do it.

Click here to read more.

5 comments:

  1. I think this is one of the most significant information for me. And i’m glad reading your article. Thanks for sharing!

    Learn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Softgen Infotech provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
    Big Data Analytics Training in Bangalore
    Tableau Training in Bangalore
    Data Science Training in Bangalore
    Workday Training in Bangalore

    ReplyDelete
  2. Nice knowledge gaining article. This post is really the best on this valuable topic. data scientist course in kanpur

    ReplyDelete
  3. Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. data analytics course in kanpur

    ReplyDelete