为什么这一刻 diff 函数 return 0 而不是 1

Why does this moment diff function return 0 instead of 1

Returns 0 个月,但这应该是 1 个月,因为从文档中我看到从一个月到下一个月的包含日期算作一个月。

console.log(moment('2020-11-06T00:00:00+00:00').diff(moment('2020-10-06T21:22:21.2976559+00:00'), 'months'))

首先,moment 已被弃用,不建议在新项目中使用 https://momentjs.com/docs/#/-project-status/

Month/year 差异讨论可以在这里看到:https://github.com/moment/moment/pull/571

如果删除时间信息,它将 return 1 如预期:console.log(moment('2020-11-06').diff(moment('2020-10-06'), 'months'));。这对我来说像是一个错误,但我想这正是 moment 预期的工作方式

我在他们的文档中找到了这个 https://momentjs.com/docs/

Note: Moments are created at evaluation time, so moment().diff(moment()) may not always return 0. See this GitHub issue for more details.

GitHub link 是: https://github.com/moment/moment/issues/5195

看看你在比较什么。

2020-10-06T21:22:21.2976559+00:00
2020-11-06T00:00:00+00:00

第二个约会的时间是00:00。第一次约会的时间是 21:22:21。你只剩下一个月了。

将时间标准化,它会起作用。

console.log(moment('2020-11-06T00:00:00').diff(moment('2020-10-06T00:00:00'), 'months'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>