Functional Weave
Code in Python

hr.length-of-service@1.0.0

impl/python.py

1,165 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 add_days, days_between  ← from dates.add-days ^1.0.0 · built alongside by fune
from .dates_add_months import add_months  ← from dates.add-months ^1.0.0 · built alongside by fune
from .hr_length_of_service_types import ServiceLength


def length_of_service(start_date: str, end_date: str) -> ServiceLength:
    """Completed years, months and days of service, both end dates included.

    The end is moved to the following day so that a service period ending on
    the eve of an anniversary counts as a whole year; forgetting that is the
    off-by-one that denies someone a statutory right by a day.
    """
    total_days = days_between(start_date, end_date) + 1
    if total_days < 1:
        raise ValueError("endDate %s is before startDate %s" % (end_date, start_date))
    end_exclusive = add_days(end_date, 1)
    months = (int(end_exclusive[0:4]) - int(start_date[0:4])) * 12 + (int(end_exclusive[5:7]) - int(start_date[5:7]))
    while months > 0 and add_months(start_date, months) > end_exclusive:
        months -= 1
    anniversary = add_months(start_date, months)
    return ServiceLength(
        years=months // 12,
        months=months % 12,
        days=days_between(anniversary, end_exclusive),
        total_days=total_days,
    )