-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
36 lines (28 loc) · 962 Bytes
/
script.js
File metadata and controls
36 lines (28 loc) · 962 Bytes
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
32
33
34
35
36
document.getElementById("ageForm").addEventListener("submit", function (e) {
e.preventDefault();
const dobInput = document.getElementById("dob").value;
const resultDiv = document.getElementById("result");
if (!dobInput) {
resultDiv.textContent = "Please enter a valid date.";
return;
}
const birthDate = new Date(dobInput);
const today = new Date();
if (birthDate > today) {
resultDiv.textContent = "Date of birth cannot be in the future.";
return;
}
let years = today.getFullYear() - birthDate.getFullYear();
let months = today.getMonth() - birthDate.getMonth();
let days = today.getDate() - birthDate.getDate();
if (days < 0) {
months--;
const prevMonth = new Date(today.getFullYear(), today.getMonth(), 0);
days += prevMonth.getDate();
}
if (months < 0) {
years--;
months += 12;
}
resultDiv.textContent = `Your age is ${years} year(s), ${months} month(s), and ${days} day(s).`;
});