【问题标题】:Calculation of duration between two dates doesn't result in expected result计算两个日期之间的持续时间不会产生预期结果
【发布时间】:2022-01-12 09:18:31
【问题描述】:

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

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

【问题讨论】:

  • 11 个月,30 天仅当开始日期在 31 天的月份中且上个月有 30 天时才相当于 1 年。 11 月 21 日加上 11 个月得到 10 月 21 日。加上 30 天得到 11 月 20 日,因为 10 月有 31 天。要使用大于周的单位持续时间,需要规则来处理此类问题。例如。应该将 1 年添加到 2 月 29 日导致 2 月 28 日还是 3 月 1 日?两者对我来说同样可行。见Difference between two dates in years, months, days in JavaScript

标签: javascript date momentjs


【解决方案1】:

如果你想要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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"&gt;&lt;/script&gt;

你的方式结果:

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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我的问题是,我需要计算孩子的年龄。有的只有几个月大,有的只有几年。这就是我想使用{ days, months, years } 解决方案的原因。这就是为什么我不能使用你的想法。
  • 您可以使用第三个参数来获取年份差异,但小数 now.diff(bday, 'years', true),不确定这是否是您要查找的内容。
  • @user3142695 - 当差值小于一年时,可能使用月份:const diff = now.diff(bday, "months");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 2014-02-28
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多