I need to calculate the exact difference between two dates in days, months and years.
I have this function:
const getAge = (dateString) => {
const today = new Date();
const birthDate = new Date(dateString);
let age = today.getFullYear() - birthDate.getFullYear();
const m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age -= 1;
}
return age;
};
It receives a date in YYYY-MM-DD format. At this time it outputs a exact number of years (6 years, or 5 if it's before "birthday").
I need it to output 5 years, 11 months and 29 days (as an example).
How can I achieve that?