2

Need to get the name of the month (ie. April) instead of the number that is compatible with a React app.

I've tried using a few JavaScript snippets, but I'm not getting the results I need.

Currently using {(new Date().getMonth()+1)} to pull the month number. To note, this is rendering outside of a component.

Ajanth
  • 2,435
  • 3
  • 20
  • 23
dooge
  • 51
  • 1
  • 9

4 Answers4

3

The simplest form would be using an array:

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let monthIndex = (new Date().getMonth());
let monthName = monthNames[monthIndex];

// render jsx
return (<div>{monthName}<div>)

In case you need to do more with date (compare, add, subtract, etc.) you might want to use a library, e.g. moment.js.

mehmetseckin
  • 3,061
  • 1
  • 31
  • 43
  • May I ask why so many examples include a predefined array with the month names? `date.toLocaleString('nl-NL', { month: 'long' })` does exactly that, right? – Y. Gherbi Jun 18 '22 at 13:05
1

Personally, I am not sure why most examples and answers default to using a predefined array with the month names. It can be easily done using the js Date object. But there might be some pitfalls since it's not the most common way of doing it. I just don't know what they are...

Example

function getMonthName(monthNumber) {
  const date = new Date()
  date.setMonth(monthNumber) // starts with 0, so 0 is January
  return date.toLocaleString('en-EN', { month: "long" })
}

getMonthName(1) // February
getMonthName(3) // April
Y. Gherbi
  • 890
  • 8
  • 22
0

You can use {['January','February',...,'December'](new Date().getMonth())}. It will pick the correct index from the months array (eg index 0 = January).

George Koniaris
  • 324
  • 2
  • 9
-1

It should be:

let monthName = monthNames[monthNumber - 1];
Run_Script
  • 2,487
  • 2
  • 15
  • 30
Dave
  • 1
  • hi Dave, thank you for your answer! could you add an explanation to your code? it's not clear what you think the author of the question got wrong, or how this is a solution. if "monthNames" is a particular array for example, please describe it (even if you think it's obvious) as it isn't mentioned in the question at all – Sasha Kondrashov Jul 28 '20 at 23:58
  • Hi Sasha, Sorry for misunderstanding! The array is zero based, so e.g. September would be at index 8! That is why I thought it might be quite clear for everyone. See also my screenshot form VS. -Sorry it looks like I can not upload images yet! – Dave Jul 29 '20 at 22:14