To format a date in JavaScript, you can use the ‘toLocaleDateString()
‘ method of the ‘Date
‘ object. This method takes two arguments: a locales string and an options object, and it returns a string representation of the date formatted according to the specified locale and options.
Here’s an example of how you can use ‘toLocaleDateString()
‘ to format a date:
const date = new Date();
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
};
const formattedDate = date.toLocaleDateString('en-US', options);
console.log(formattedDate); // Outputs: "December 18, 2022"
The ‘locales
‘ argument specifies the language and region to use when formatting the date. The ‘options
‘ object allows you to specify various formatting options, such as the format of the year, month, and day.
You can find a full list of available options and their meanings in the Intl.DateTimeFormat documentation. ( click to visit)
If you want to format the date in a specific way that is not supported by ‘toLocaleDateString()
‘, you can also use string templates or string concatenation to build the formatted date string manually.
For example:
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // months are zero-based
const day = date.getDate();
const formattedDate = `${month}/${day}/${year}`;
console.log(formattedDate); // Outputs: "12/18/2022"
RELATED : Loop through an array in JavaScript [Every Method]