Functional Weave
Code in Python

dates.age@1.0.0

impl/typescript.ts

970 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { isLeapYear, parseIsoDate } from "./dates_add_days.ts";  ← from dates.add-days ^1.0.0 · built alongside by fune

/**
 * Completed years on `onDate`. A person attains an age at the start of their
 * birthday; for a 29 February birthday in a year without one, the birthday is
 * taken to be 1 March (Age of Legal Capacity (Scotland) Act 1991 s.6(2), and
 * the UK reading of Family Law Reform Act 1969 s.9), not 28 February.
 */
export function age(birthDate: string, onDate: string): number {
  const birth = parseIsoDate(birthDate);
  const on = parseIsoDate(onDate);
  if (onDate < birthDate) {
    throw new RangeError(`onDate ${onDate} is before birthDate ${birthDate}`);
  }
  let birthdayMonth = birth.month;
  let birthdayDay = birth.day;
  if (birth.month === 2 && birth.day === 29 && !isLeapYear(on.year)) {
    birthdayMonth = 3;
    birthdayDay = 1;
  }
  let years = on.year - birth.year;
  if (on.month < birthdayMonth || (on.month === birthdayMonth && on.day < birthdayDay)) years -= 1;
  return years;
}