Skip to content

Commit 817bf45

Browse files
committed
add months and days
1 parent cde2cb9 commit 817bf45

File tree

2 files changed

+31
-16
lines changed

2 files changed

+31
-16
lines changed

projects/age-calculator/index.js

+29-14
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,43 @@ const resultEl = document.getElementById("result");
44

55
function calculateAge() {
66
const birthdayValue = birthdayEl.value;
7+
// console.log(birthdayValue)
78
if (birthdayValue === "") {
89
alert("Please enter your birthday");
910
} else {
1011
const age = getAge(birthdayValue);
11-
resultEl.innerText = `Your age is ${age} ${age > 1 ? "years" : "year"} old`;
12+
resultEl.innerText = `Your age is ${age.years=0?'':age.years} ${"years"} ${age.months=0?'':age.months} ${"months"} ${age.days=0?"":age.days} ${"days"} old`;
1213
}
1314
}
15+
// here cancel 0 display doesn'gitt work
1416

1517
function getAge(birthdayValue) {
16-
const currentDate = new Date();
17-
const birthdayDate = new Date(birthdayValue);
18-
let age = currentDate.getFullYear() - birthdayDate.getFullYear();
19-
const month = currentDate.getMonth() - birthdayDate.getMonth();
20-
21-
if (
22-
month < 0 ||
23-
(month === 0 && currentDate.getDate() < birthdayDate.getDate())
24-
) {
25-
age--;
18+
19+
const today = new Date();
20+
const birth = new Date(birthdayValue);
21+
let age = {};
22+
23+
let yearDiff = today.getFullYear() - birth.getFullYear();
24+
let monthDiff = today.getMonth() - birth.getMonth();
25+
let dayDiff = today.getDate() - birth.getDate();
26+
27+
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
28+
yearDiff--;
29+
if (monthDiff < 0) {
30+
monthDiff += 12;
31+
}
32+
if (dayDiff<0) {
33+
const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 0);
34+
dayDiff += lastMonth.getDate();}
35+
// dayDiff = today.getDate() + (new Date(today.getFullYear(), today.getMonth(), 0)).getDate() - birth.getDate();
36+
}
37+
38+
age.years = yearDiff;
39+
age.months = monthDiff;
40+
age.days = dayDiff;
41+
42+
return age;
2643
}
2744

28-
return age;
29-
}
3045

31-
btnEl.addEventListener("click", calculateAge);
46+
btnEl.addEventListener("click", calculateAge);

projects/age-calculator/style.css

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
body {
2-
margin: 0;
2+
margin: 10;
33
padding: 20px;
44
font-family: "Montserrat", sans-serif;
55
background-color: #f7f7f7;
@@ -30,7 +30,7 @@ h1 {
3030

3131
label {
3232
font-weight: bold;
33-
margin-bottom: 10px;
33+
margin-bottom: 20px;
3434
}
3535

3636
input {

0 commit comments

Comments
 (0)