Home >Web Front-end >JS Tutorial >How to Convert a JavaScript Date String from 'Sun May 11, 2014' to 'yyyy-mm-dd' Format?

How to Convert a JavaScript Date String from 'Sun May 11, 2014' to 'yyyy-mm-dd' Format?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 12:17:16727browse

How to Convert a JavaScript Date String from

Modifying JavaScript Dates to yyyy-mm-dd Format

Question: Convert a JavaScript date in the format "Sun May 11,2014" to "2014-05-11".

Initial Attempt:

One common approach involves splitting the date string, manipulating its components, and reassembling them. However, this method yielded the same original format.

Solution:

Embrace the built-in toISOString() method:

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

This code returns an ISO 8601 timestamp, which aligns with the desired yyyy-mm-dd pattern.

Timezone Handling (Optional):

To handle time zone considerations, consider incorporating the following modifications suggested by @exbuddha:

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

The above is the detailed content of How to Convert a JavaScript Date String from 'Sun May 11, 2014' 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