How to format date in javascript as DD-MMM-YYYY


ou can format a JavaScript Date object as DD-MMM-YYYY using the toLocaleDateString() method with the appropriate options.

Here’s an example:

const date = new Date();
const options = { day: '2-digit', month: 'short', year: 'numeric' };
const formattedDate = date.toLocaleDateString('en-US', options);
console.log(formattedDate); // "01-May-2023"

In this example, we’re creating a new Date object with the current date and time. We’re then calling the toLocaleDateString() method on the date object and passing it the desired locale and options as parameters.

The options object specifies the desired date format, including the day as a two-digit number, the month as a short abbreviation, and the year as a four-digit number.

If you need the month in uppercase letters, you can modify the options object as follows:

const date = new Date();
const options = { day: '2-digit', month: 'short', year: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(date).toUpperCase();
console.log(formattedDate); // "01-MAY-2023"

In this example, we’re creating a new DateTimeFormat object with the desired locale and options. We’re then calling the format() method on the formatter object and passing it the date to format. Finally, we’re converting the formatted date to uppercase using the toUpperCase() method.