@aemrobe
Posted
Thanks for the explanation. I have done this challenge before and I have used a another method to calculate the age. I wanted to know the concept behind you have written the code specially the if else one
var years = presentDate.getFullYear() - userDate.getFullYear();
var months = presentDate.getMonth() - userDate.getMonth();
var days = presentDate.getDate() - userDate.getDate();
const daysPreviousMonth = new Date(presentDate.getFullYear(), presentDate.getMonth(), 0).getDate();
const daysPreviousPreviousMonth = new Date(presentDate.getFullYear(), presentDate.getMonth() - 1, 0).getDate();
if (days < 0) {
months--;
days = daysPreviousMonth + days;
}
if (days < 0) {
months--;
days = daysPreviousPreviousMonth + days;
}
if (months < 0) {
years--;
months = 12 + months;
}
print(days, months, years);
}
@aemrobe
This code snippet calculates the difference between two dates (userDate
and presentDate
) to determine the age. It does this by separately calculating the years, months, and days of difference. The variables years
, months
, and days
capture the raw difference in years, months, and days, respectively.
The if
and else
blocks handle cases where the days or months are negative, which can happen if the user's date (userDate
) is later than the current date (presentDate
). When the days are negative, the code subtracts one month from the total months and adjusts the number of days accordingly, taking into account the number of days in the previous months.
Furthermore, the code deals with the case where the difference in months is also negative by subtracting one year from the total years and adjusting the number of months to be a correct positive value.
The final result is printed using the print(days, months, years)
function. This will result in the calculated age difference based on the provided dates.