I have a registered some users in my app with their birth date. I'm trying to have a field called "age" that should show a number representing amount of years since born until today.
ie;
I have a user born 01-jan-2017 (today is 04-feb-2018)
the age output should be: 1 year old
and
I have a user born 05-feb-2017 (today is 04-feb-2018)
the age output should be: 0 year old
I have tried many thing... converting new Date() to time in milis and subtract new Date(birthdate) in milis. then making a new date with the dif and converting to years. but it doesn't return the correct amount of years always....
Finaly I have tried to implement the answer for this post Convert birthday to age in angularjs which have the exact same main question as I. I even see people commenting "thanks this works well" etc.... and it has 28 up votes. but I still don't get the correct value (years) always.... why!!??
Here is my implementation:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'birthdate'
})
export class BirthdatePipe implements PipeTransform {
transform(date: any, args?: any): any {
const ageDifMs = Date.now() - new Date(date).getTime();
const ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
I tested it with following dates (remember today is: 04-feb-2018):
01-feb-2017 | birthdate = 0 should be 1
18-jan-2017 | birthdate = 1 should be 1
22-jan-2017 | birthdate = 1 should be 1
31-jan-2017 | birthdate = 0 should be 1
Is it really supposed to be difficult to calculate the years a person have lived based on their birth date without using some fancy framework? can that really be true? or am I missing something? Why are people in the other question having success with that code? is it a typescript/angular2 difference that is causing it to fail for me, since it seems to work in js/angular1....?