-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (36 loc) · 1.47 KB
/
index.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
32
33
34
35
36
37
38
39
40
41
42
43
44
const btnEl = document.getElementById("btn");
const dateEl = document.querySelector(".date");
const resultEl = document.getElementById("result");
btnEl.addEventListener("click", function() {
// Get the selected date value
const selectedDate = new Date(dateEl.value);
console.log("clicked");
if (isNaN(selectedDate.getTime())) {
resultEl.textContent = "Please enter a valid date.";
return;
}
// Get the current date
const today = new Date();
// Calculate the difference in years
let years = today.getFullYear() - selectedDate.getFullYear();
// Calculate the difference in months and adjust the year if necessary
let months = today.getMonth() - selectedDate.getMonth();
if (months < 0) {
years--;
months += 12;
}
// Calculate the difference in days and adjust the month if necessary
let days = today.getDate() - selectedDate.getDate();
if (days < 0) {
months--;
if (months < 0) {
years--;
months += 11; // Because we've already adjusted years
}
// Adjust days by adding the number of days in the previous month
const previousMonth = new Date(today.getFullYear(), today.getMonth(), 0).getDate();
days += previousMonth;
}
// Update result label
resultEl.textContent = `Your calculated age is ${years} years, ${months} months, and ${days} days old.`;
});