-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
31 lines (26 loc) · 859 Bytes
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const btnEl = document.getElementById("btn");
const birthdayEl = document.getElementById("birthday");
const resultEl = document.getElementById("result");
function calculateAge() {
const birthdayValue = birthdayEl.value;
if (birthdayValue === "") {
alert("Please enter your birthday");
} else {
const age = getAge(birthdayValue);
resultEl.innerText = `Your age is ${age} ${age > 1 ? "years" : "year"} old`;
}
}
function getAge(birthdayValue) {
const currentDate = new Date();
const birthdayDate = new Date(birthdayValue);
let age = currentDate.getFullYear() - birthdayDate.getFullYear();
const month = currentDate.getMonth() - birthdayDate.getMonth();
if (
month < 0 ||
(month === 0 && currentDate.getDate() < birthdayDate.getDate())
) {
age--;
}
return age;
}
btnEl.addEventListener("click", calculateAge);