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

How to Generate an ISO 8601-Formatted Timestamp in JavaScript?

DDD
DDDOriginal
2024-11-15 12:02:02572browse

How to Generate an ISO 8601-Formatted Timestamp in JavaScript?

How to Output an ISO 8601-Formatted Timestamp in JavaScript

When displaying dates in a standardized format, ISO 8601 provides a structured and consistent way. This article delves into how to generate an ISO 8601-formatted string in JavaScript.

To address the question posed, you can utilize JavaScript's built-in function called toISOString() that natively converts a Date object into an ISO 8601 string. For instance:

var date = new Date();
date.toISOString(); // Output: "2023-03-08T10:15:30.000Z"

If, by any chance, your browser lacks support for toISOString(), the following alternative code snippet can be utilized:

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";
    };
  }());
}

By incorporating this fallback code, you can ensure compatibility with older browsers.

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