How to convert a JSON date serialized by an ASMX web service to a JavaScript Date object

JSON doesn’t have a standard way to represent a date. You can read about the reasons behind this here.

If you are using an ASMX web service returning JSON then you’ll find it serializes the DateTime object to a string that looks like this:

/Date(1278943200000)/

The numer in this string is the number of milliseconds since January 1st 1970 UTC, and this number can be used as a constructor argument to the JavaScript Date object.  So all we need to do is extract the number of milliseconds from the string.  This can be done easily using the regular expression shown in the post linked above.

var dateString = "/Date(1278943200000)/";
var date = new Date(parseInt(dateString.replace(/\/Date\((\d+)\)\//, '$1')));

In the above example I’ve manually set the date string, but you may get this from an AJAX response from the ASMX web service.  I then create a new Date object by using the regular expression and parsing the result at an integer.

Posted on by Joe in Ajax, ASP.NET, JavaScript

5 Responses to How to convert a JSON date serialized by an ASMX web service to a JavaScript Date object

  1. Tom

    I found this both interesting and informative.

  2. Craig

    Thanks for this simple regex… I wondered why my date was coming back all funky. Didn’t realize asmx was doing that!

    Awesome.

  3. Joe

    Glad it helped Craig

    Joe

  4. Renata

    Thanks for this post. It was very useful.
    I just wondering, how the jsod dat can be converted into c# date object.

  5. Joe

    Renata

    That’s what this post is about. Line 2 in the above example is doing exactly that. Or do you have a different date format in your JSON?

    Cheers
    Joe

Add a Comment