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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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