@Jahan-Shah
Posted
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