Need to get the name of the month (ie. April) instead of the number that is patible 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 ponent.
Need to get the name of the month (ie. April) instead of the number that is patible 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 ponent.
- Is using a predefined array of months an acceptable solution? – Rowan Baker-French Commented Apr 17, 2019 at 15:53
- 1 Possible duplicate of Get month name from Date – JKL Commented Apr 17, 2019 at 15:57
4 Answers
Reset to default 3The 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 (pare, add, subtract, etc.) you might want to use a library, e.g. moment.js.
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 mon 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
You can use {['January','February',...,'December'](new Date().getMonth())}
. It will pick the correct index from the months array (eg index 0 = January).
It should be:
let monthName = monthNames[monthNumber - 1];