计算两个日期之间的持续时间不会产生预期结果

Calculation of duration between two dates doesn't result in expected result

这是我通过使用当前日期和生日来简单计算年龄的方法:

const now = moment(current)
const bday = moment(birthday)
const diff = now.diff(bday)
const { _data } = moment.duration(diff)
console.log(_data);

我设置了这些值,应该恰好相差一年...

current: 2021-11-20T23:00:00.000Z
birthday: 2020-11-20T23:00:00.000Z

...这导致了这些时刻日期:

Moment<2021-11-21T00:00:00+01:00>
Moment<2020-11-21T00:00:00+01:00>

令人惊讶的是我得到了这个结果:

{
    milliseconds: 0,
    seconds: 0,
    minutes: 0,
    hours: 0,
    days: 30,
    months: 11,
    years: 0
}

但我希望 1 year。这是对自己的误解吗?

diff 结果为 31536000000

如果你想要 years 的差异,试试这个:

const current = '2021-11-20T23:00:00.000Z';
const birthday = '2020-11-20T23:00:00.000Z';

const now = moment(current);
const bday = moment(birthday);

const diff = now.diff(bday, 'years');

console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

您的方式导致:

const current = '2021-11-20T23:00:00.000Z';
const birthday = '2020-11-20T23:00:00.000Z';

const now = moment(current);
const bday = moment(birthday);

const diff = moment.duration(now.diff(bday)).asYears();

console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>