I need to get the date format as \'DD-Mon-YYYY\' in javascript. I had asked a question, and it got marked duplicate to jQuery date formatting
But, the answers provi
Using the Intl object (or via toLocaleString) is somewhat problematic, but it can be made precise using the formatToParts method and manually putting the parts in order, e.g.
function formatDate(date = new Date()) {
let {day, month, year} = new Intl.DateTimeFormat('en', {
day:'2-digit',
month: 'short',
year: 'numeric'
}).formatToParts(date).reduce((acc, part) => {
if (part.type != 'literal') {
acc[part.type] = part.value;
}
return acc;
}, Object.create(null));
return `${day}-${month}-${year}`;
}
console.log(formatDate());
Using reduce on the array returned by formatToParts trims out the literals and creates an object with named properties that is then assigned to variables and finally formatted.
This function doesn't always work nicely for languages other than English though as the short month name may have punctuation.