-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
88 lines (76 loc) · 2.52 KB
/
script.js
File metadata and controls
88 lines (76 loc) · 2.52 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const ageCalculate = () => {
const today = new Date();
const inputDate = new Date(document.getElementById("date-input").value);
const birthDetails = {
date: inputDate.getDate(),
month: inputDate.getMonth() + 1,
year: inputDate.getFullYear(),
};
const currentYear = today.getFullYear();
const currentMonth = today.getMonth() + 1;
const currentDate = today.getDate();
if (isFutureDate(birthDetails, currentYear, currentMonth, currentDate)) {
alert("Not Born Yet");
displayResult("-", "-", "-");
return;
}
const { years, months, days } = calculateAge(
birthDetails,
currentYear,
currentMonth,
currentDate
);
displayResult(days, months, years);
};
const isFutureDate = (birthDetails, currentYear, currentMonth, currentDate) => {
return (
birthDetails.year > currentYear ||
(birthDetails.year === currentYear &&
(birthDetails.month > currentMonth ||
(birthDetails.month === currentMonth &&
birthDetails.date > currentDate)))
);
};
const calculateAge = (birthDetails, currentYear, currentMonth, currentDate) => {
let years = currentYear - birthDetails.year;
let months, days;
if (currentMonth < birthDetails.month) {
years--;
months = 12 - (birthDetails.month - currentMonth);
} else {
months = currentMonth - birthDetails.month;
}
if (currentDate < birthDetails.date) {
months--;
const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1;
const daysInLastMonth = getDaysInMonth(lastMonth, currentYear);
days = daysInLastMonth - (birthDetails.date - currentDate);
} else {
days = currentDate - birthDetails.date;
}
return { years, months, days };
};
const getDaysInMonth = (month, year) => {
const isLeapYear = year % 4 === 0 && (year % 100 != 0 || year % 400 === 0);
const getDaysInMonth = [
31,
isLeapYear ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
return getDaysInMonth[month - 1];
};
const displayResult = (bdate, bMonth, bYear) => {
document.getElementById("years").textContent = bYear;
document.getElementById("months").textContent = bMonth;
document.getElementById("days").textContent = bdate;
};
document.getElementById("calc-age-btn").addEventListener("click", ageCalculate);