Skip to content

Instantly share code, notes, and snippets.

@iboB
Last active February 20, 2021 08:48
Show Gist options
  • Save iboB/1363623 to your computer and use it in GitHub Desktop.
Save iboB/1363623 to your computer and use it in GitHub Desktop.
Simple age calculator in JavaScript (I use it in some about-me HTMLs)
function calcAge(year, month, day) {
const now = new Date();
let age = now.getFullYear() - year;
const mdif = now.getMonth() - month + 1; // jan is 0 in getMonth
if (mdif < 0) {
// not birthday yet
--age;
}
else if (mdif === 0) {
// maybe birthday?
var ddif = now.getDate() - day;
if (ddif < 0) --age; // not birthday yet
}
return age;
}
@iboB
Copy link
Author

iboB commented Dec 20, 2019

You don't have all the checks. See the code from above. What does it do:
Line 3: estimate the age of the person by subtracting the birth year from the current year. It might seem that this is enough, but technically if the birthday hasn't passed yet this is one year more than the age of the person. That's why:
Line 5: check if the current month is before birth month (difference is negative). If it is, then the birthday of the person isn't here yet, and our calculation from line 3 is one more than needed. And we're done
Line 9: If the condition of line 5 isn't true, check if the month of the person is the current month (difference is zero) (if it's greater than zero, then the birthday has passed and our calculation from line 3 was correct). If it is the current month, then we also need to check the day.
Line 12: If the current date is before the birth date, then the birthday isn't here and we need to correct the calculation from line 3.
Line 14: Return the (potentially corrected by one from line 7 or line 12) age

@bennami
Copy link

bennami commented Dec 20, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment