Home >Web Front-end >JS Tutorial >How to Convert a JavaScript Date String from 'Sun May 11, 2014' to 'yyyy-mm-dd' Format?
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!