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

How to Generate ISO 8601 Formatted Strings in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 09:55:10759browse

How to Generate ISO 8601 Formatted Strings in JavaScript?

Outputting ISO 8601 Formatted Strings in JavaScript

To render the "title" portion of an ISO 8601 formatted string, consider utilizing the following approaches:

Using the toISOString() Method

JavaScript's Date object provides the toISOString() method, which directly returns a string in the ISO 8601 format.

const date = new Date();
const isoString = date.toISOString();

Custom Format Function

If toISOString() is unavailable, you can implement a custom function to generate ISO 8601 strings:

function isoDate(msSinceEpoch) {
  const d = new Date(msSinceEpoch);
  return (
    d.getUTCFullYear() +
    '-' +
    (d.getUTCMonth() + 1).toString().padStart(2, 0) +
    '-' +
    d.getUTCDate().toString().padStart(2, 0) +
    'T' +
    d.getUTCHours().toString().padStart(2, 0) +
    ':' +
    d.getUTCMinutes().toString().padStart(2, 0) +
    ':' +
    d.getUTCSeconds().toString().padStart(2, 0)
  );
}

console.log(isoDate(Date.now()));

Polyfill for toISOString()

For browsers without support for toISOString(), you can use the following polyfill:

if (!Date.prototype.toISOString) {
  (function() {
    function pad(number) {
      const 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'
      );
    };
  })();
}

The above is the detailed content of How to Generate 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