dooge
dooge

Reputation: 51

React: Get month name instead of number

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.

Upvotes: 2

Views: 9764

Answers (4)

Producdevity
Producdevity

Reputation: 882

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

Upvotes: 1

mehmetseckin
mehmetseckin

Reputation: 3107

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.

Upvotes: 3

Dave
Dave

Reputation: 1

It should be:

let monthName = monthNames[monthNumber - 1];

Upvotes: -1

George Koniaris
George Koniaris

Reputation: 334

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

Upvotes: 0

Related Questions