How to parse JSON to receive a Date object in JavaScript?

I have a following piece of JSON:

\/Date(1293034567877)\/

which is a result of this .NET code:

var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

Now the problem I am facing is how to create a Date object from this in JavaScript. All I could find was incredible regex solution (many containing bugs).

It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.

I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).

Is there really no way to do it in an elegant way?

Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT


Solution 1:

The JSON.parse function accepts an optional DateTime reviver function. You can use a function like this:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.

Solution 2:

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

Solution 3:

This answer from Roy Tinker here:

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

As he says: 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.

Another option is to simply format your information properly on the ASP side such that JavaScript can easily read it. Consider doing this for your dates:

DateTime.Now()

Which should return a format like this:

7/22/2008 12:11:04 PM

If you pass this into a JavaScript Date constructor like this:

var date = new Date('7/22/2008 12:11:04 PM');

The variable date now holds this value:

Tue Jul 22 2008 12:11:04 GMT-0700 (Pacific Daylight Time)

Naturally, you can format this DateTime object into whatever sort of string/int the JS Date constructor accepts.

Solution 4:

If you use the JavaScript style ISO-8601 date in JSON, you could use this, from MDN:

const jsonDate = (new Date()).toJSON();
const backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z

To create an ISO-8601 date string:

myDate.toISOString()

Solution 5:

You can convert JSON Date to normal date format in JavaScript.

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