DataContractJsonSerializer and DateTime values

In using the DataContractJsonSerializer beware of DateTime instances which have been instantiated as non-UTC. If you declare without explicitly assigning a DateTime you get the same as default(DateTime), this is 01/01/01 00:00:00 (0 ticks) with a DateTimeKind of Unspecified. When the DataContractJsonSerializer looks at this value (or a Local datetime), it will try to convert it to UTC by subtracting the time zone ala UTC standard notation, this results in a date time that is less that 0 ticks and an out of range exception if you are west of GMT.

The solution is to always instantiate as UTC and you can avoid this issue. As mentioned previously you cannot interrupt the serialization process for DateTime on a member of the DataContract serializer family.

Another pain in the rectum is that it will change the accuracy of your DateTime value from 100 ns to 1 ms, so if you are relying on this value being the same for change tracking or any other means then this will produce problems.

posted @ Tuesday, March 17, 2009 11:13 AM

Print

Comments on this entry:

# re: DataContractJsonSerializer and DateTime values

Left by Srihari at 2/24/2010 10:44 PM
Gravatar
Hi,

I am building an RESTFull WCF service. My data contract types having the DateTime fields. If I assign the DateTime value of the field to DateTime.MinValue, the format of DateTime showing in the rendered output for Json is "Date(-62135596800000)" . In rest of the cases it is showing the format "2007-10-30T06:56:00"

I tested the Json output with different dateTime values. Those are,

1. If DateTime field value is "DateTime.Now", then Json output format is Date(1266960616682-0800)
2. If DateTime field value is "DateTime.MinValue", then Json output format is Date(-62135596800000)
3. if we asssign any date explicitly, the json output format is "2007-10-30T06:56:00"

I want single DateTime format through out my json output. you help me on this.

Thanks,
Srihari

Your comment:



 (will not be displayed)


 
 
 
Please add 4 and 6 and type the answer here:
 

Live Comment Preview: