Home > Back-end >  Convert date to Month Year using Javascript
Convert date to Month Year using Javascript

Time:10-13

I have a Date() object in Javascript. How can I convert it to show "Month Year" (example: Oct 2021).

I tried the following code and it works too. However, I have to convert a lot of dates to this format and it has performance issues.

  const date = new Date();
  const month = date.toLocaleString('default', { month: 'short' });
  const year = date.toLocaleString('default', { year: 'numeric' });

Note: I don't want to use JQuery or other libraries.

CodePudding user response:

If performance is such a concern, why not just reduce some complexity and use getMonth()/getYear() and manually map the abbreviated month names?

const date = new Date();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
console.log(months[date.getMonth()]   " "   date.getFullYear())

It's provably faster than the other methods posited here, even with the requirement to declare months.

  • Related