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

javascript - How to get month index from month name using date-fns library - Stack Overflow

programmeradmin4浏览0评论

I need to get the month index number from the month name using the date-fns library. Earlier I was using moment.js, it was straightforward with moment.js

  moment().month('March').format('M'); 
// Month name will be variable and I don't want to use static dictionary to get index number

How to achieve the same using the date-fns library? I thought to use format(date, 'M'); but it needs plete date and only month name is available.

Please suggest. Thanks!

I need to get the month index number from the month name using the date-fns library. Earlier I was using moment.js, it was straightforward with moment.js

  moment().month('March').format('M'); 
// Month name will be variable and I don't want to use static dictionary to get index number

How to achieve the same using the date-fns library? I thought to use format(date, 'M'); but it needs plete date and only month name is available.

Please suggest. Thanks!

Share Improve this question asked Sep 29, 2021 at 18:29 pk786pk786 2,4303 gold badges22 silver badges25 bronze badges 1
  • I don't think so date-fns has any thing like that available at the moment github./date-fns/date-fns/blob/master/src/getMonth/index.ts – navnath Commented Sep 29, 2021 at 19:04
Add a ment  | 

2 Answers 2

Reset to default 4

I think this is what you need

If you are using date-fns library

function getMonthCount(month){
    const result = getMonth(new Date(`${month} 1`))+1;
}

If you don't want to use any library

function getMonthCount(month){
    const sometime= new Date(`${month} 1`);
    console.log(sometime.getMonth()+1);
}

NOTE: this will return month in range [1,12]

date-fns es with handy functions out of the box

import {getMonth} from 'date-fns'

const date = new Date()

const month = getMonth(date) + 1

getMonth returns a number, you add +1 because it starts with 0. The result you'll get is the number of the month. If let's say the month is March, you'll get 3

发布评论

评论列表(0)

  1. 暂无评论