diff --git a/projects/age-calculator/index.js b/projects/age-calculator/index.js index b2888ee..f35a213 100644 --- a/projects/age-calculator/index.js +++ b/projects/age-calculator/index.js @@ -4,27 +4,55 @@ const resultEl = document.getElementById("result"); function calculateAge() { const birthdayValue = birthdayEl.value; + // console.log(birthdayValue) if (birthdayValue === "") { alert("Please enter your birthday"); } else { const age = getAge(birthdayValue); - resultEl.innerText = `Your age is ${age} ${age > 1 ? "years" : "year"} old`; + const yeartext = age.years === 0 ? "" : age.years.toString() + "years"; + const monthtext = age.months === 0 ? "" : age.months.toString() + "months"; + const daytext = + age.days === 0 + ? " " + : age.days.toString().concat(age.days > 1 + ? "days" + : "day"); + // console.log(daytext) + // in Java script null,0,"", false and undefined all ==.Here use ===, otherwise + // always choose false, means the second option + resultEl.innerText = `Your age is ${yeartext} ${monthtext} ${daytext} old`; } } +// here cancel 0 display doesn'gitt work +// still got a bit issue, is 1 months display. will improve it later on. +// fixed. there are 4 string joining method. 1 use + 2.contact() 3 `{} 4 .join in array function getAge(birthdayValue) { - const currentDate = new Date(); - const birthdayDate = new Date(birthdayValue); - let age = currentDate.getFullYear() - birthdayDate.getFullYear(); - const month = currentDate.getMonth() - birthdayDate.getMonth(); + const today = new Date(); + const birth = new Date(birthdayValue); + let age = {}; - if ( - month < 0 || - (month === 0 && currentDate.getDate() < birthdayDate.getDate()) - ) { - age--; + let yearDiff = today.getFullYear() - birth.getFullYear(); + let monthDiff = today.getMonth() - birth.getMonth(); + let dayDiff = today.getDate() - birth.getDate(); + + if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) { + yearDiff--; + if (monthDiff < 0) { + monthDiff += 12; + } + if (dayDiff < 0) { + const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 0); + dayDiff += lastMonth.getDate(); + } + // dayDiff = today.getDate() + (new Date(today.getFullYear(), today.getMonth(), 0)).getDate() - birth.getDate(); } + age.years = yearDiff; + age.months = monthDiff; + age.days = dayDiff; + // console.log(age.days) + return age; } diff --git a/projects/age-calculator/style.css b/projects/age-calculator/style.css index 0229675..a0a8dd5 100644 --- a/projects/age-calculator/style.css +++ b/projects/age-calculator/style.css @@ -1,5 +1,5 @@ body { - margin: 0; + margin: 10; padding: 20px; font-family: "Montserrat", sans-serif; background-color: #f7f7f7; @@ -30,7 +30,7 @@ h1 { label { font-weight: bold; - margin-bottom: 10px; + margin-bottom: 20px; } input {