Functional Weave
Code in Python

dates.age@1.0.0

impl/python.py

927 bytes · the Python 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.

from .dates_add_days import is_leap_year, parse_iso_date  ← from dates.add-days ^1.0.0 · built alongside by fune


def age(birth_date: str, on_date: str) -> int:
    """Completed years on ``on_date``.

    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.
    """
    birth = parse_iso_date(birth_date)
    on = parse_iso_date(on_date)
    if on_date < birth_date:
        raise ValueError("onDate %s is before birthDate %s" % (on_date, birth_date))
    birthday_month, birthday_day = birth.month, birth.day
    if birth.month == 2 and birth.day == 29 and not is_leap_year(on.year):
        birthday_month, birthday_day = 3, 1
    years = on.year - birth.year
    if (on.month, on.day) < (birthday_month, birthday_day):
        years -= 1
    return years