Prisoner ZERO
Prisoner ZERO

Reputation: 14176

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(1283457528340)/

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

Upvotes: 2

Views: 6992

Answers (3)

calumj_dev
calumj_dev

Reputation: 25

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.

Upvotes: 0

Thai
Thai

Reputation: 11364

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)

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

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]

Upvotes: 1

Related Questions