如何使用 Moment.js 计算 X 天后的年龄?

How do I get my age in X days using Moment.js?

我当前的密码是

function ageInNDays(days) {
  return moment.duration(
    moment('1990-10-10').diff(
    moment().add(days, 'days'))
  );
}

.add(days, 'days') 今天,然后将它与过去的某个日期进行比较。但是,moment.duration 并不总是 return 过去的日历年数。它将一年定义为 365 天,returns 已经过去了多少年。

编辑:我仍在寻找我的年龄作为年数。也许如果可能的话,类似于 moment.duration() 看起来的 20 年、5 个月和 10 天格式。

如果我的生日是 1992 年 3 月 5 日,那么我的年龄应该只在日历经过 3 月 5 日时增加。我的剩余天数应该只有在每个月的 5 号过去后才会重置。

EDIT2:我现在唯一的想法是

age = moment().add(days, 'days').year() - moment('1995-01-05').year()
if ((today's date + added days) < birthday's date)
  --age

如果您真的想以天为单位查找年龄,您可以使用:

moment.duration(moment() - moment('1990-10-10')).asDays();

更新

您还可以使用它来增加您当前年龄的天数:

function ageInNDays(days) {
    var age = moment.duration(moment() - moment('1990-10-10'));
    return age.add(days, 'd').asDays();
}

来自 the documentation

Trying to convert years to days makes no sense without context. It is much better to use moment#diff for calculating days or years between two moments than to use Durations.

所以看起来使用 diff 就是答案:

function ageInNDays(days) { 
    return moment().add(days, 'days').diff('1990-10-10', 'years', true); 
}

// ageInNDays(1000);
// 27.977483271480484

请注意,这给出了年的小数(根据第三个参数)。如果您不希望它四舍五入(默认实现会这样做),您可以截断它:

function ageInNDays(days) { 
    return Math.floor(moment().add(days, 'days').diff('1990-10-10', 'years', true)) + ' years'; 
}

// ageInNDays(1000);
// 27 years

为小数差异添加参数 boolean true

var currentDate = new Date();
var diff = moment(currentDate).diff('1990-10-10', 'years',true);
console.log("Year", diff);

示例

这将根据日期回答 21.23