To format a date as a string in a specific format using JavaScript, you can use the toLocaleDateString()
method or the Intl.DateTimeFormat
object. Here's an example of each method:
toLocaleDateString()
:const date = new Date(); // Get current date
const formattedDate = date.toLocaleDateString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
console.log(formattedDate); // Output: MM/DD/YYYY, e.g. 01/31/2022
Intl.DateTimeFormat
:const date = new Date(); // Get current date
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
const formattedDate = formatter.format(date);
console.log(formattedDate); // Output: MM/DD/YYYY, e.g. 01/31/2022
In both methods, we specify the desired format by passing an options object with year
, month
, and day
properties. numeric
is used for two-digit numbers and 2-digit
is used for zero-padded two-digit numbers. The result will be the date formatted as a string in the specified format.