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;
}
@bennami
Copy link

bennami commented Dec 19, 2019

what about the day of birth. i get a -15 difference if it is the same day of the current date. would -15 work?

@iboB
Copy link
Author

iboB commented Dec 19, 2019

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, say year, day, month ?

@iboB
Copy link
Author

iboB commented Dec 19, 2019

I updated the function to have a bit more modern style. It's still exactly the same and still seems to be correct

@bennami
Copy link

bennami commented Dec 20, 2019

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!

@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