@@ -4,28 +4,43 @@ const resultEl = document.getElementById("result");
4
4
5
5
function calculateAge ( ) {
6
6
const birthdayValue = birthdayEl . value ;
7
+ // console.log(birthdayValue)
7
8
if ( birthdayValue === "" ) {
8
9
alert ( "Please enter your birthday" ) ;
9
10
} else {
10
11
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` ;
12
13
}
13
14
}
15
+ // here cancel 0 display doesn'gitt work
14
16
15
17
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 ;
26
43
}
27
44
28
- return age ;
29
- }
30
45
31
- btnEl . addEventListener ( "click" , calculateAge ) ;
46
+ btnEl . addEventListener ( "click" , calculateAge ) ;
0 commit comments