Home > Web Front-end > JS Tutorial > How to format a Date as an ISO 8601 string in JavaScript?

How to format a Date as an ISO 8601 string in JavaScript?

DDD
Release: 2024-11-14 16:49:02
Original
203 people have browsed it

How to format a Date as an ISO 8601 string in JavaScript?

How to Output an ISO 8601 Formatted String in JavaScript

To render the title portion of the given snippet, you can utilize the inbuilt toISOString() function. Here's how to use it:

const date = new Date();
const isoDate = date.toISOString();
Copy after login

This will return a string in ISO 8601 format, which includes the date and time components:

"2023-05-24T16:03:45.123Z"
Copy after login

Alternatively, if 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';
    };
  }());
}

console.log(new Date().toISOString());
Copy after login

The above is the detailed content of How to format a Date as an ISO 8601 string in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template