0 votes
in Education by (1.7m points)
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"

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by (1.7m points)
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())

Run code snippetExpand snippet
...