开发者

How do I convert this JSON datetime?

The following string was returned from a JSON formatted response object and I want to parse it into something useful: /Date(128345开发者_运维知识库7528340)/

How do I parse it using JavaScript into something user-friendly?


It's the number of milliseconds since epoch.

This function extracts a number from a string, and returns a Date object created from that time number.

function dateFromStringWithTime(str) {
    var match;
    if (!(match = str.match(/\d+/))) {
        return false;
    }
    var date = new Date();
    date.setTime (match[0] - 0);
    return date;
}

For example,

console.log(dateFromStringWithTime('/Date(1283457528340)/').toString());

The output is:

Fri Sep 03 2010 02:58:48 GMT+0700 (ICT)


Depends. What does that value represent? Assuming UNIX timestamp milliseconds (adjust otherwise), you can extract the value, then apply parseInt and construct a new Date object with it.

var str     = "/Date(1283457528340)/";
var matches = str.match(/([0-9]+)/);
var d       = parseInt(matches[0]);
var obj     = new Date(d);

You should then be able to use the Date object as normal. This is untested and may have typos/bugs, but the idea should be sound.

Edit: matches[1] -> matches[0]


function parseJsonDate(jsonDate) {
    var epochMillis = jsonDate;
    var d = new Date(parseInt(epochMillis.substr(6)));
    return d;
}

The code above will give you a date formatted in a way that is useful in a given view.

The parameter passed into the function (jsonDate) is the string you are trying to convert and the line return d is returning the date formatted nicely.

Simply another way to get the date you need.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜