计算并显示年,月和日的人的年龄

时间:2019-11-30 15:02:05

标签: javascript

我是从API获得的JSON数据,需要计算年龄:

{"fullname":"Nikita","email":"test@demo.com","city":"London","mobile":"08888888888","birthday"{"year":1980,"month":7,"day":23}}

当前,我将出生日期显示为{{anon.birthday}},结果是1980-7-23。我想显示年龄。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

您可以使用moment.js npm i moment

import * as moment from 'moment';

// Get the date of birth as a moment
const birthDateMoment: moment.Moment = moment(`${yourObject.birthday.day}/${yourObject.birthday.month}/${yourObject.birthday.year}, 'DD/MM/YYYY');

选项1:使用duration:获取从现在(moment())到birthDate之间的持续时间

const durationLife = moment.duration(moment().diff(birthDateMoment))
durationLife.years();

选项2:使用diff

moment().diff(birthDateMoment, 'years');

选项3:time from

birthDateMoment.from(moment());

答案 1 :(得分:1)

您应该能够从{{age}}

获得年龄

在加载时添加它

this.getAge();

然后计算

getAge() {
    const now = new Date();
    const birthdate = new Date(this.anon.birthday.split('-')[0], this.anon.birthday.split('-')[1], this.anon.birthday.split('-')[2]);
    const timeDiff = now.getTime() - birthdate.getTime();
    this.age = Math.floor( timeDiff / (365 * 24 * 60 * 60 * 1000));
  }