Home >Web Front-end >JS Tutorial >How to Convert a JavaScript Date to YYYY-MM-DD Format?

How to Convert a JavaScript Date to YYYY-MM-DD Format?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 18:17:09777browse

How to Convert a JavaScript Date to YYYY-MM-DD Format?

Transform JavaScript Date to YYYY-MM-DD Format

Converting a date in the format "Sun May 11,2014" to "2014-05-11" using JavaScript can be achieved efficiently.

One method involves leveraging the built-in toISOString method, which returns a date in the ISO 8601 format, including both date and time components. To extract only the date portion, you can split the result at the 'T' character, isolating the date string. For example:

let yourDate = new Date('Sun May 11,2014');
const date = yourDate.toISOString().split('T')[0];
console.log(date); // Logs: "2014-05-11"

Alternatively, if you need to handle time zone differences, you can use the getTimezoneOffset and getTime methods to adjust the date before converting it to ISO 8601 format:

const offset = yourDate.getTimezoneOffset();
yourDate = new Date(yourDate.getTime() - (offset * 60 * 1000));
const date = yourDate.toISOString().split('T')[0];
console.log(date); // Logs: "2014-05-11"

With these methods, you can effectively convert JavaScript dates to the desired YYYY-MM-DD format, facilitating date handling and formatting in your applications.

The above is the detailed content of How to Convert a JavaScript Date to YYYY-MM-DD Format?. 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