1

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,215
  • 1
  • 18
  • 22
dooge
  • 41
  • 1
  • 9

3 Answers3

1

The simplest form would be using an array:

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

// 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
  • 2,901
  • 1
  • 29
  • 40
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
  • 314
  • 2
  • 9
-1

It should be:

let monthName = monthNames[monthNumber - 1];
Run_Script
  • 2,332
  • 2
  • 12
  • 26
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