moment js在不同情况下计算月份不同
moment js calculates months differently in different instances
我正在使用 Moment JS 添加日期。我想从今天开始增加 2 个月。我发现这两行代码相加两个月给出了不同的结果
// Today 29 03 2021
moment().add(2, 'M').format('DD MM YYYY') // prints 29 03 2021
moment().add(1, 'M').add(1, 'M').format('DD MM YYYY') //prints 28 03 2021
谁能解释一下为什么我们会得到不同的结果,以及使用 moment js add 函数的正确方法是什么。
谢谢
这是因为 .add()
的工作方式:
Special considerations for months and years
If the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.
moment([2010, 0, 31]); // January 31
moment([2010, 0, 31]).add(1, 'months'); // February 28
我正在使用 Moment JS 添加日期。我想从今天开始增加 2 个月。我发现这两行代码相加两个月给出了不同的结果
// Today 29 03 2021
moment().add(2, 'M').format('DD MM YYYY') // prints 29 03 2021
moment().add(1, 'M').add(1, 'M').format('DD MM YYYY') //prints 28 03 2021
谁能解释一下为什么我们会得到不同的结果,以及使用 moment js add 函数的正确方法是什么。
谢谢
这是因为 .add()
的工作方式:
Special considerations for months and years
If the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.
moment([2010, 0, 31]); // January 31 moment([2010, 0, 31]).add(1, 'months'); // February 28