Javascript Format Date to DD-Mon-YYY


To get the current date in the DD-Mon-YYYY format (e.g., “01-May-2023”), you can use the Date object to get the day, month, and year components of the current date, and then use an array of month names to get the abbreviated month name.

Here’s an example:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const date = new Date();
const day = date.getDate().toString().padStart(2, '0');
const monthIndex = date.getMonth();
const year = date.getFullYear();
const monthName = months[monthIndex];
const formattedDate = `${day}-${monthName}-${year}`;
console.log(formattedDate); // e.g. "01-May-2023"

In this example, we’re creating an array of month names, which we’ll use to get the abbreviated month name for the current date. We’re then creating a new Date object with the current date and time.

We’re using the getDate() method to get the day component of the date, and the getMonth() method to get the zero-based index of the month component. We’re using the getFullYear() method to get the year component.

We’re then using the padStart() method to ensure that the day component has two digits (e.g., “01” instead of “1”).

Finally, we’re using the month index to get the abbreviated month name from the months array, and concatenating the day, month name, and year components into a string in the format DD-Mon-YYYY.