Last active
February 20, 2021 08:48
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
yes! i had to add a an else if to check for the month.
https://github.com/bennami/js-complete-course/blob/master/04-dates/03-age-by-select/script.js
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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