【问题标题】:How to get month index from month name using date-fns library如何使用 date-fns 库从月份名称中获取月份索引
【发布时间】:2021-11-21 16:08:40
【问题描述】:

我需要使用 date-fns 库从月份名称中获取月份索引号。之前我使用moment.js,使用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

如何使用date-fns 库实现相同的功能?我想使用format(date, 'M');,但它需要完整的日期,并且只有月份名称可用。

请提出建议。谢谢!

【问题讨论】:

标签: javascript date-fns


【解决方案1】:

我想这就是你需要的

如果你使用 date-fns 库

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

如果你不想使用任何库

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

注意:这将返回 [1,12] 范围内的月份

【讨论】:

  • new Date(${month} 1) 这里的 1 是什么?
  • 我在这里所做的是将月份转换为日期。 new Date(${month} 1) 这将返回一个日期,该日期将是该月的第一天。所以这里的 1 告诉你需要每月的第一天
  • 知道了,谢谢!这对我有用。
猜你喜欢
  • 2020-10-25
  • 2018-03-01
  • 2017-10-03
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
相关资源
最近更新 更多