Search code examples
sqljquerydatejs

Converting .net sql datetime to jquery using date.js


I have an ajax post to which I am getting values from sql database. My datatype in sql is datetime what it returns is:

Orderdate: "/Date(-62135578800000)/"

Now using date.js I am trying to do the following:

orderdate = Date.parse(response.d[post].Orderdate);

orderdate.toString('MM/dd/yyyy')

but that keeps coming up with this error:

Uncaught TypeError: Cannot call method 'toString' of null 

what am i doing wrong? i don't get it :(

EDIT: here's my complete code,

$.ajax({
    type: "POST",
    url: "../ajaxcalls.asmx/Test",
    data: "{id:'" + id + "'}",
    contentType: "application/json",
    dataType: "json",
    success: function (response) {
        for (var post in response.d) {
            orderdate = Date.parse(response.d[post].Orderdate);
            console.log(orderdate);
            console.log(response.d[post].Orderdate);
            console.log(orderdate.toString('MM/dd/yyyy'));
        }

    }

});

Solution

  • You can't pass the .NET JSON date implementation straight to JavaScript Date.parse(); you need to extract the milliseconds since epoch out and pass that to the Date constructor.

    var orderdate = new Date(parseInt(response.d[post].Orderdate.replace("/Date(", "").replace(")/",""), 10));
    
    orderdate.toString('MM/dd/yyyy');
    

    for more on the rationale behind the date representation used by ASP.NET, see

    One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "/Date(628318530718)/". For some rationale behind this rather contrived choice of encoding, see "Inside ASP.NET AJAX’s JSON date and time string."