Working with JSON dates in Javascript

Working with JSON when passing data back and forth to a server is usually a joy - except when it comes to dates. Try passing a 'datetime' field from C# through JSON and you'll end up with a field that looks like:

/Date(1224043200000)/

You'll also quickly discover that this is not a format that can simply be passed in to the javascript Date class via the constructor, and it can't be easily parsed by anything else. At this point, many developers just punt and pass the properly formatted string back, instead of passing the date itself back.

I recently discovered there is a nifty way to parse this date data in Javascript:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor. Note that we are NOT using 'eval' to parse the date.

Using this method, you can use all of the date formatting methods built in to Javascript:

date.toDateString();