How can I convert a JavaScript Date object into a custom string format?

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.

In my work, I often encountered similar requirements and eventually transitioned from handcrafted solutions to using small utility modules. While a custom function like the one demonstrated is straightforward enough, I found that wrapping such logic within a dedicated helper function often improves readability and maintainability across projects. It might be worth considering even a lightweight library such as date-fns if you ever start handling more complex formatting or internationalization needs. Personally, a clear and tested implementation saves debugging time in the long run.