Home > Web Front-end > JS Tutorial > How to Convert a JavaScript Date to ISO 8601 Format (yyyy-mm-dd)?

How to Convert a JavaScript Date to ISO 8601 Format (yyyy-mm-dd)?

Patricia Arquette
Release: 2024-12-30 10:47:10
Original
714 people have browsed it

How to Convert a JavaScript Date to ISO 8601 Format (yyyy-mm-dd)?

Converting JavaScript Date to ISO 8601 Format

Question: I have a JavaScript date in the format "Sun May 11, 2014". How can I convert it to the ISO 8601 format of "2014-05-11"?

Initial Attempt:

The code snippet below attempts to format the date using the split() method but fails to achieve the desired result:

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + '').split(' ');
    d[2] = d[2] + ',';

    return [d[0], d[1], d[2], d[3]].join(' ');
}
Copy after login

Solution:

To convert the date to ISO 8601 format, leverage the built-in toISOString() method. This method returns the date in a format that conforms to the ISO 8601 standard:

let yourDate = new Date();
yourDate.toISOString().split('T')[0];
Copy after login

The toISOString() method returns a string in the following format:

yyyy-mm-ddThh:mm:ss.ssssssZ
Copy after login

The split('T')[0] part of the code retrieves only the date portion of the string, excluding the time and timezone information.

Additional Note:

To handle timezone properly, modify the code as follows:

const offset = yourDate.getTimezoneOffset();
yourDate = new Date(yourDate.getTime() - (offset * 60 * 1000));
return yourDate.toISOString().split('T')[0];
Copy after login

The above is the detailed content of How to Convert a JavaScript Date to ISO 8601 Format (yyyy-mm-dd)?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template