我当前的代码是
function ageInNDays(days) {
return moment.duration(
moment('1990-10-10').diff(
moment().add(days, 'days'))
);
}
我.add(days, 'days')
到今天,然后将其与过去的某个日期进行比较。但是,moment.duration
并不总是返回过去的日历年数。它将一年定义为 365 天,并返回其中已经过去了多少年。
编辑:我仍在寻找我的年龄。如果可能的话,也许类似于 20 年、5 个月和 10 天的格式,类似于 moment.duration() 的外观。
如果我的生日是 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
最佳答案
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
请注意,它给出了年的小数部分(通过第三个参数)。如果您不希望它四舍五入(默认实现会这样做),您可以 chop 它:
function ageInNDays(days) {
return Math.floor(moment().add(days, 'days').diff('1990-10-10', 'years', true)) + ' years';
}
// ageInNDays(1000);
// 27 years
关于javascript - 如何使用 Moment.js 获取 X 天后的年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620547/