19

Am working with json api that represents dates like this

"date" : "/Date(1356081900000)/"

I want to turn this into regular javascript Date.

The only way I can think of solving this problem is to do a replace on everything leaving the timestamp which I can then "convert".

This works but it just looks wrong.

My question. Can I do this in better way?

UPDATE

 unix_timestamp = jsonDate.replace('/Date(', '').replace(')/', '');

 newDate = new Date(+unix_timestamp + 1000*3600);
jamjam
  • 3,171
  • 7
  • 34
  • 39
  • 1
    Did you see this other post? [Convert a Unix timestamp to time in Javascript](http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript) – Miguel-F Dec 21 '12 at 16:53

3 Answers3

13

Duplicate of How to format a JSON date?.

Accepted solution was:

var date = new Date(parseInt(jsonDate.substr(6)));
Community
  • 1
  • 1
antila
  • 364
  • 1
  • 4
11

Try something like this:-

 var d = new Date(unix_timestamp*1000);

or

 var d = new Date([UNIX Timestamp] * 1000);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    this works for me, ten a simple `return t.toLocaleDateString() + ' ' + t.toLocaleTimeString();` in my function – elporfirio Nov 18 '15 at 17:10
0

The Date constructor accepts a Unix timestamp.

function cleanDate(d) {
    return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));
}

cleanDate("/Date(1356081900000)/"); // => Fri Dec 21 2012 04:25:00 GMT-0500 (EST)
josh3736
  • 139,160
  • 33
  • 216
  • 263