You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

dateUtils.keyToMoment获取月份错误,请求代码问题排查指导

问题排查与解决

你遇到的月份显示错误,核心原因是 Moment.js 的 month() 方法采用0索引机制:返回值范围是0(对应1月)到11(对应12月),而非日常使用的1-12。从截图看,newMonth 显示10,实际对应的是11月,这是Moment.js的默认行为,并非代码bug。

修正代码

要得到1-12的常规月份数值,只需在原代码基础上加1:

const newMonth = todayMoment.month() + 1;

额外优化提示

  1. 你导入了 dateUtils,但调用 keyToMoment 时用了 this.dateUtils,如果当前上下文没有挂载 dateUtils 到 this,会引发报错,建议统一为:
    const todayMoment = dateUtils.keyToMoment(today);
    
  2. 也可以用Moment.js的format()方法直接获取格式化后的月份:
    • todayMoment.format('M'):返回1-12的月份字符串
    • todayMoment.format('MM'):返回带前导零的01-12月份字符串
      转成数值的示例:
    const newMonth = Number(todayMoment.format('M'));
    

内容的提问来源于stack exchange,提问作者Anand Somani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:01:41