JSON Date Serialization and Time Zones JSON Date Serialization and Time Zones json json

JSON Date Serialization and Time Zones


When you're trying to control offsets, don't rely on DateTimeKind.Unspecified. It has a few quirks that are often interpreted as Unspecified == Local. The only way to get Json.Net to specifically encode the correct offset (regardless of ISO or MS format) is to pass it a DateTimeOffset instead of a DateTime.

// Start with the UTC time, for example your m.ErrorDate.// Here I demonstrate with UtcNow.  Any DateTime with .Kind = UTC is ok.var dt = DateTime.UtcNow;// Use the appropriate time zone, here I demonstrate with EST.var tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");// Get the offset from UTC for the time zone and date in question.var offset = tzi.GetUtcOffset(dt);// Get a DateTimeOffset for the date, and adjust it to the offset found above.var dto = new DateTimeOffset(dt).ToOffset(offset);// Serialize to jsonvar json = JsonConvert.SerializeObject(dto, new JsonSerializerSettings    {        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,    });// The json should now contain the correct time and offset information.// For example,  "\/Date(1358789156229-0500)\/"

Now hopefully you will find that the javascript controls you are using will honor the offset and apply it appropriately. If not, then the rest of the problem is specific to the control you are using.


Here is a long discussion on the exact situation that I have been in. http://www.telerik.com/community/forums/aspnet-mvc/grid/grids-and-dates.aspx

Bottom line, if you are using the Microsoft JSON date format, it will always reflect the date in UTC as the number of milliseconds (ticks) from 1/1/1970 UTC. There's no way for me to auto-convert the time to local on the server and send what it should be down via JSON to the Kendo Grid as the Kendo Grid control instantiates the date from the ticks in JS as UTC. When displaying this date, it will auto-convert the value to the browser's local time zone.

The only way to show my server's converted date value from the server is to send the date via JSON as a string to the client.


We ran into this problem as well. As you note, the problem is actually happening on the client side. By using a request end handler in your grid, you can convert the date back to UTC. Example found here:

http://www.kendoui.com/code-library/mvc/grid/using-utc-time-on-both-client-and-server-sides.aspx