开发者

using jquery to return dates

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);

        }
    });
}开发者_StackOverflow中文版);


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


$(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;
        }
    });
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜