Submitted over 1 year ago
Age Calculator with responsive UI made using grid
@RobertPietraru
Design comparison
SolutionDesign
Solution retrospective
How do you validate dates and find how much time has passed?
For date validation I'm checking if the day, month and year I put in is the same in the date object.
For finding how much time has passed I get the milliseconds and divide by 365, 30, etc. That's not accurate though, so I'm looking for a better approach
Community feedback
- @Jahan-ShahPosted over 1 year ago
Hey Robert 👋, congratulations on solving this challenge
Your date validation is good, but if you want to calculate age in more concise and readable code you can look at my following code:
function calculateAge(day, month, year) { const today = new Date(); const birthDate = new Date(year, month - 1, day); //Date Validation const isDayValid = birthDate.getDate() === day; const isMonthValid = birthDate.getMonth() === month - 1; const isYearValid = birthDate.getFullYear() === year; if (!isDayValid || !isMonthValid || !isYearValid) { isInputValid.value = false; return; } //calculating difference of current date and birthdate let ageYears = today.getFullYear() - birthDate.getFullYear(); let ageMonths = today.getMonth() - birthDate.getMonth(); let ageDays = today.getDate() - birthDate.getDate(); if (ageMonths <= 0) { ageMonths += 12; ageYears--; } if (ageDays < 0) { const lastMonthDate = new Date( today.getFullYear(), today.getMonth(), 0 ).getDate(); ageDays += lastMonthDate; ageMonths--; } //Age: console.log(ageYears, ageMonths, ageDays); }
I hope this will help
Regards,
Shahjahan
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord