最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I convert this JSON datetime? - Stack Overflow

programmeradmin0浏览0评论

The following string was returned from a JSON formatted response object and I want to parse it into something useful: /Date(1283457528340)/

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

The following string was returned from a JSON formatted response object and I want to parse it into something useful: /Date(1283457528340)/

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

Share Improve this question asked Jan 3, 2011 at 16:55 Prisoner ZEROPrisoner ZERO 14.2k21 gold badges100 silver badges147 bronze badges 1
  • Can you provide other useful details in that post? Is that a Unix timestamp? Is it UTC encoded and needs to be converted to local time? Does it really return as that particular string /Date(...)/ and you need to parse out the numbers? – jcolebrand Commented Jan 3, 2011 at 16:56
Add a ment  | 

3 Answers 3

Reset to default 5

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)

  1. 暂无评论