0

I am making a JQuery call to a web method and returning JSON, but I have a problem when I try to return dates, they come back in the format /Date(1298073600000)/. Can anybody help?

$(document).ready(function() {

    $.ajax(
    {
        type: "POST",
        url: "/CDServices.asmx/GetWeekEndingDates",
        data: "{}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",

        success: function(msg) {

            alert(msg.d.LastWeekEndingDate);

        }
    });
});
0

3 Answers 3

2

If msg.d.LastWeekEndingDate contains /Date(1298073600000)/, you should apply a little regex to strip the timestamp:

var mydate = new Date(+msg.d.LastWeekEndingDate.match(/\/Date\((\w+)\)\//)[1]);

The regex returns a string literal which needs to get converted into a Number. I used the + infront of the expression to do that. Outcome is:

console.log(mydate);   // === Sat Feb 19 2011 01:00:00 GMT+0100 {}

Update:

The Date object exposes several methods to you. For instance:

console.log([mydate.getDate(), mydate.getMonth()+1, mydate.getFullYear()].join('/'));

would return 19/2/2011.

See https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date

Sign up to request clarification or add additional context in comments.

Comments

0
$(document).ready(function() {
    $.ajax(
    {
        type: "POST",
        url: "/CDServices.asmx/GetWeekEndingDates",
        data: "{}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",

        success: function(msg) {
            var aDate = new Date(msg.d.LastWeekEndingDate);
            var month = aDate.getMonth() + 1;
            var day = aDate.getDate();
            var year = aDate.getFullYear();
            var usethis = day + "/" + month + "/" + year;
        }
    });
});

4 Comments

Hi, When 19/02/2011 00:00:00 is returned, this just gives me Nan/Nan/Nan
if you use alert(msg.d.LastWeekEndingDate); and see 1298073600000. So my code works fine.
I have removed the timestamp, but strangely a msg.d.LastWeekEndingDate of 19/2/2011, when your code is applied to it gives a 'usethis' value of 2/7/2012..?
what's the value of msg.d.LastWeekEndingDate for "19/2/2011". And also check aDate.toString() value
0

var dtE = /^/Date((-?[0-9]+))/$/.exec(msg.d.LastWeekEndingDate); if (dtE) { var dt = new Date(parseInt(dtE[1], 10)); alert(dt); }

In reference to SO question, this needs to be modified as your requirements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.