Search code examples
javascriptdatetimeiso8601

How do I output an ISO 8601 formatted string in JavaScript?


I have a Date object. How do I render the title portion of the following snippet?

<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>

I have the "relative time in words" portion from another library.

I've tried the following:

function isoDate(msSinceEpoch) {

   var d = new Date(msSinceEpoch);
   return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
          d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();

}

But that gives me:

"2010-4-2T3:19"

Solution

  • There is already a function called toISOString():

    var date = new Date();
    date.toISOString(); //"2011-12-19T15:28:46.493Z"
    

    If, somehow, you're on a browser that doesn't support it, I've got you covered:

    if (!Date.prototype.toISOString) {
      (function() {
    
        function pad(number) {
          var r = String(number);
          if (r.length === 1) {
            r = '0' + r;
          }
          return r;
        }
    
        Date.prototype.toISOString = function() {
          return this.getUTCFullYear() +
            '-' + pad(this.getUTCMonth() + 1) +
            '-' + pad(this.getUTCDate()) +
            'T' + pad(this.getUTCHours()) +
            ':' + pad(this.getUTCMinutes()) +
            ':' + pad(this.getUTCSeconds()) +
            '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
            'Z';
        };
    
      }());
    }
    
    console.log(new Date().toISOString())