Home  >  Article  >  Web Front-end  >  How to Generate an ISO 8601 Date String in JavaScript?

How to Generate an ISO 8601 Date String in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 16:26:13294browse

How to Generate an ISO 8601 Date String in JavaScript?

ISO 8601 Date String in JavaScript

When working with dates in JavaScript, you may need to output the date in ISO 8601 format. This format includes the year, month, day, hour, minute, and second, and it is useful for internationalization and data exchange.

Using toISOString()

Most modern browsers support the Date.prototype.toISOString() method to generate an ISO 8601-formatted string. The following code demonstrates its usage:

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

The string includes the date (2011-12-19), time (15:28:46), and fractional seconds (493 milliseconds). The "Z" at the end indicates that the time is in UTC.

Handling Legacy Browsers

If you need to support older browsers that do 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 this polyfill, you can use toISOString() even in browsers that do not support it natively.

The above is the detailed content of How to Generate an ISO 8601 Date String 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