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(' '); }
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];
The toISOString() method returns a string in the following format:
yyyy-mm-ddThh:mm:ss.ssssssZ
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];
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!