73

I have a timestamp like this 1331209044000 and I want to convert it to an ISO 8601 timestamp. How can I convert it using JavaScript?

I use the jQuery "timeago" plugin - http://timeago.yarp.com/

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63
  • 1
    See http://en.wikipedia.org/wiki/ISO_8601 for more information about the standard. I'm afraid you simply have to build a string based on the `Date` components. – Jacob Oct 12 '12 at 22:55
  • 2
    This looks promising: http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript – Xitalogy Oct 12 '12 at 23:07

2 Answers2

126

Assuming your timestamp is in milliseconds (or you can convert to milliseconds easily) then you can use the Date constructor and the date.toISOString() method.

var s = new Date(1331209044000).toISOString();
s; // => "2012-03-08T12:17:24.000Z"

If you target older browsers which do not support EMCAScript 5th Edition then you can use the strategies listed in this question: How do I output an ISO 8601 formatted string in JavaScript?

Community
  • 1
  • 1
maerics
  • 151,642
  • 46
  • 269
  • 291
  • This is ECMAScript 5 - See here for compatibility and fallback code: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString – Xitalogy Oct 12 '12 at 23:09
  • 29
    Do not forget, that unix timestamp is in seconds, but Javascript counts in miliseconds. So it is actually `new Date(timestamp * 1000).toISOString();`. – Josef Kufner Sep 16 '15 at 23:43
  • 4
    This comment is for future me: IT HAS TO BE IN MILISECONDS ! – Tom Smykowski Sep 09 '20 at 12:06
1

The solution i used, thanks to the links provided

// convert to ISO 8601 timestamp
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
}

var d = new Date(parseInt(date));
console.log(ISODateString(d));
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63