Calculate Exact Age In Years

Compute exact years, months and days between a birth date and a reference date using UTC date-only arithmetic.

JavascriptForm Validation

Code

javascriptsnippet
41 lines
export function calculateAge(birthDate, asOf = new Date()) {
  const birth = toDateOnly(birthDate);
  const reference = toDateOnly(asOf);
  if (birth > reference) throw new RangeError("birthDate must not be in the future");
  let totalMonths = (reference.getUTCFullYear() - birth.getUTCFullYear()) * 12
    + (reference.getUTCMonth() - birth.getUTCMonth());
  if (reference.getUTCDate() < birth.getUTCDate()) totalMonths -= 1;
  const anchor = addMonthsClamped(birth, totalMonths);
  const days = Math.floor((reference.getTime() - anchor.getTime()) / 86400000);
  return {
    years: Math.floor(totalMonths / 12),
    months: totalMonths % 12,
    days,
    totalMonths,
    totalDays: Math.floor((reference.getTime() - birth.getTime()) / 86400000),
  };
}

function addMonthsClamped(date, months) {
  const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1));
  const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
  target.setUTCDate(Math.min(date.getUTCDate(), lastDay));
  return target;
}

function toDateOnly(value) {
  if (value instanceof Date) {
    if (Number.isNaN(value.getTime())) throw new RangeError("invalid date");
    return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate()));
  }
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value));
  if (!match) throw new TypeError("expected YYYY-MM-DD or Date");
  const year = Number(match[1]);
  const month = Number(match[2]) - 1;
  const day = Number(match[3]);
  const date = new Date(Date.UTC(year, month, day));
  if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) {
    throw new RangeError("invalid calendar date");
  }
  return date;
}

How it works

The working surface is the functions totalMonths, calculateAge, addMonthsClamped and toDateOnly — everything else is wiring.

Invalid states are rejected up front: it throws RangeError and TypeError instead of continuing with bad data.

The result comes back as an object carrying days, totalMonths.

What to watch for

  • The guard birth > reference short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function calculateAge(birthDate, asOf = new Date()

Treat calculateAge as the API: import it, and ignore the supporting code.

The call returns days, totalMonths — destructure what you need at the call site.

Key statements

return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate()));
if (birth > reference) throw new RangeError("birthDate must not be in the future");
if (Number.isNaN(value.getTime())) throw new RangeError("invalid date");

Interactive Tools for This Topic

FAQ

Does `calculateAge` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
What happens on invalid input?
`RangeError` and `TypeError` is raised at the guard (`birth > reference`), so invalid state never reaches the main logic.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `totalMonths`, `calculateAge`, `addMonthsClamped` at load time.