I’m looking for a way to transform a JavaScript Date object into a specific string format, such as ‘DD-MMM-YYYY’ (for example, 10-Aug-2010). I’ve encountered several approaches, but none have produced the exact formatting I need. Could someone guide me on how to accomplish this conversion efficiently? Below is an example of an alternative solution using a distinct function and variables:
function convertDate(inputDate) {
let numericDay = inputDate.getDate();
let monthPosition = inputDate.getMonth();
let completeYear = inputDate.getFullYear();
const abbreviatedMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return (numericDay < 10 ? '0' + numericDay : numericDay) + '-' + abbreviatedMonths[monthPosition] + '-' + completeYear;
}
const exampleDate = new Date('2010-08-10');
console.log(convertDate(exampleDate));
Any insights or alternative methods would be greatly appreciated.