0

I got this as JSON data from the API and need to calculate the age:

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

Currently, I'm showing the date of birth as {{anon.birthday}} which results in 1980-7-23. I would like to show the age instead. How can I go about doing this?

C.OG
  • 6,236
  • 3
  • 20
  • 38
Nikita Gupta
  • 827
  • 1
  • 7
  • 13
  • What have you tried to get the age? Can you post the sample code? – ulmas Nov 30 '19 at 15:18
  • Does this answer your question? [Calculate age given the birth date in the format YYYYMMDD](https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd) – Joel Joseph Nov 30 '19 at 16:34

2 Answers2

2

You can use 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');

Option1: using duration: Get the duration time between now (moment()) and the birthDate

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

Option 2: Use diff

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

Option 3: time from

birthDateMoment.from(moment());
1

You should be able to get the age from {{age}}

Add this on load

this.getAge();

Then to calculate

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));
  }
Elaine Byene
  • 3,868
  • 12
  • 50
  • 96