A code snippet for determining/calculating age from a given date. This snippet can be useful for calculating the age from a date on the fly, rather than having to store it in a data store.
functioncalcAge(dobStr) {
// 1: create a new `Date` object from `dobStr`const birthDate = newDate(dobStr);
// 2: create a new `Date` object for "today"const today = newDate();
// 3: calculate difference in years between birth year and current yearlet age = today.getFullYear() - birthDate.getFullYear();
// 4: calculate difference in months between birth month and current monthconst monthDifference = today.getMonth() - birthDate.getMonth();
if (
// 5.1: current month is earlier than the birth month?
monthDifference < 0// 5.2: or, same month but current day is earlier than birth day?
|| (monthDifference === 0 && today.getDate() < birthDate.getDate())
) {
// 5.3: subtract `1` from the age
age--;
}
// 6: return calculated agereturn age;
}