-
-
Save iboB/1363623 to your computer and use it in GitHub Desktop.
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; | |
} |
I updated the function to have a bit more modern style. It's still exactly the same and still seems to be correct
thank you! i am learning js and this was one of the assignments!
here is my solution, kind of still not working but i think i will use your method!
https://github.com/bennami/js-complete-course/blob/master/04-dates/03-age-by-select/script.js
thanks!
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
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
This is from a bit more than 8 years ago (verified by calling this function 😄). How did you even come across this?
Anyway, even though it's old-school js written in a non-js style, this function seems to be correct to me.
With what arguments are you calling this function? Are you sure you're supplying
year, month, day
and not some other permutation, sayyear, day, month
?