billingDateInMonth function

DateTime billingDateInMonth(
  1. int year,
  2. int month,
  3. int anchorDay
)

The billing date for anchorDay within month of year, with the anchor CLAMPED to the month's length so it is always a real date.

For example anchor 31 yields Jan 31, Feb 28 (or 29 in a leap year), Apr 30. anchorDay must be 1..31; out-of-range input is a programming error.

Example:

// Anchor 31 in February 2024 (leap) clamps to the 29th.
billingDateInMonth(2024, 2, 31); // 2024-02-29

Audited: 2026-06-12 11:26 EDT

Implementation

DateTime billingDateInMonth(int year, int month, int anchorDay) {
  _checkAnchor(anchorDay);

  // Clamp the anchor down to the last day so a short month never overflows into
  // the following month (the failure DateTime(year, month, 31) would cause).
  final int lastDay = _daysInMonth(year, month);
  final int day = anchorDay < lastDay ? anchorDay : lastDay;
  return DateTime(year, month, day);
}