by Andreas

Converting JSON date string to javascript date object

JSON dates come in a format that isn’t directly convertable to Javascript date objects (e.g. /Date(1349301600000+0200)/ ). This can cause a bit of headache, but there is a very simple way to convert this to a native date object.

After stripping off the initial “/Date” part using substr, parseInt will return only the integers and ignore the trailing “/”. The result is an integer value that can be used in the native javascript Date constructor.

This is what goes on under the hood:

1. Original JSON date



2. After substr(6)



3. After parseInt()



Finally I am using DatePicker from the jQuery UI library to format the date to a custom JSON date:

// parse JSON formatted date to javascript date object
var date = new Date(parseInt(jsonDate.substr(6)));

// format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", date);


On the server side I recommend using the Json.NET framework by James Newton-King (available as a NuGet). It contains several settings for handling dates depending on what you’re running client side. If you’re using KnockoutJS for instance, the ko.toJSON method will return your date object in UTC format (which means the date might suddenly be a day off, with an offset set to +2 hours my current timezone).

My quick-fix using DateTime.ToLocalTime() will work, but I am sure there is a more elegant way of getting your local time directly in the Json deserialization process:

// parse JSON
var timeRec = JsonConvert.DeserializeObject<JSONTimeRecord>(jsonString, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// convert date to local time
updatedRecord.Date = timeRec.Date.ToLocalTime();


At least that works fine – for now..