最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: Get month name instead of number - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Apr 17, 2019 at 16:49 Ajanth 2,5153 gold badges20 silver badges23 bronze badges asked Apr 17, 2019 at 15:47 doogedooge 511 silver badge9 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 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 (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];
发布评论

评论列表(0)

  1. 暂无评论