I possess a date string in the form Sun May 11, 2014
. What is the best way to transform it into the format 2014-05-11
using JavaScript?
function formatDate(inputDate) {
const dateObj = new Date(inputDate);
const year = dateObj.getFullYear();
const month = String(dateObj.getMonth() + 1).padStart(2, '0');
const day = String(dateObj.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
const date = 'Sun May 11, 2014';
console.log(formatDate(date));
The code snippet returns the same output format Sun May 11, 2014
. How can I adjust it to get the desired format?
Try using Date.toISOString()
and slice to format the date into yyyy-mm-dd
:
function formatDate(inputDate) {
const dateObj = new Date(inputDate);
return dateObj.toISOString().slice(0, 10);
}
const date = 'Sun May 11, 2014';
console.log(formatDate(date));
This approach leverages toISOString()
for streamlined conversion.
To convert a date like Sun May 11, 2014
to yyyy-mm-dd
format, another approach is using JavaScript’s Date
object methods in combination with Intl.DateTimeFormat
. This provides a flexible way to format the date with the specific components you need.
Here’s a practical example:
function formatDate(inputDate) {
const dateObj = new Date(inputDate);
const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
const formattedDateArray = new Intl.DateTimeFormat('en-CA', options).formatToParts(dateObj);
const year = formattedDateArray.find(entry => entry.type === 'year').value;
const month = formattedDateArray.find(entry => entry.type === 'month').value.padStart(2, '0');
const day = formattedDateArray.find(entry => entry.type === 'day').value.padStart(2, '0');
return `${year}-${month}-${day}`;
}
const date = 'Sun May 11, 2014';
console.log(formatDate(date)); // Output: '2014-05-11'
This solution uses the Intl.DateTimeFormat
to ensure the correct representation of year, month, and day components across various locales. It formats the date according to the Canadian format (i.e., yyyy-mm-dd
), making it quite convenient without manually adjusting the string output from toISOString
. This method is particularly useful if you need to handle dates in a locale-sensitive manner.