Home >Web Front-end >JS Tutorial >How to Output ISO 8601 Formatted Strings in JavaScript?

How to Output ISO 8601 Formatted Strings in JavaScript?

DDD
DDDOriginal
2024-11-13 05:22:02805browse

How to Output ISO 8601 Formatted Strings in JavaScript?

Outputting ISO 8601 Formatted Strings in JavaScript

You have a Date object and want to render the ISO 8601 formatted string for its title, as seen in the following example:

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

Your attempts to create the ISO date string using the getUTC*() methods have not been successful.

Solution

JavaScript provides a built-in function called toISOString() that returns the date and time in ISO 8601 format. You can use it as follows:

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

If for some reason your browser does not support toISOString(), you can use the following polyfill:

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';
    };

  }());
}

With the polyfill in place, you can use the toISOString() function to generate the ISO 8601 formatted string.

The above is the detailed content of How to Output ISO 8601 Formatted Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn