DEV Community

dipotanchangya
dipotanchangya

Posted on

Which one is the better function for calculating age?

//#FUNCTION 1
function calcAge (dob) {
const currentYear = new Date(Date.now()).getFullYear();
const birthYear = new Date(dob).getFullYear();
return currentYear - birthYear
}

//#FUNCTION 2
function Person(name, dob) {
this.name = name;
// this.age = age;
this.birthday = new Date(dob);
this.calculateAge = function(){
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}

I find it hard to understand function 2, it uses unix time.
The other one is very reader friendly, at least for me.
Your opinions are welcome.

Top comments (2)

Collapse
 
fnh profile image
Fabian Holzer

The both functions return the age after the birthday has passed, regardless whether it has actually passed or not. So unless a person is born on first of january, the implementations return a incorrect result for some part of the current year.

Collapse
 
dipotanchangya profile image
dipotanchangya

Thank you for pointing that out. I wanted to keep it simple and just get the age, but it turns out it's not accurate. Could you recommend a better function, one that returns YY-MM-DD-HH-SS?