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.

3 comments: