clampDayOfMonth function

int clampDayOfMonth ({@required int year, @required int month, @required int day })

Takes a date that may be outside the allowed range of dates for a given month in a given year and returns the closest date that is within the allowed range.

For example:

February 31, 2013 => February 28, 2013

When jumping from month to month or from leap year to common year we may end up in a month that has fewer days than the month we are jumping from. In that case it is impossible to preserve the exact date. So we "clamp" the date value to fit within the month. For example, jumping from March 31 one month back takes us to February 28 (or 29 during a leap year), as February doesn't have 31-st date.

Implementation

int clampDayOfMonth({
  @required int year,
  @required int month,
  @required int day,
}) =>
    day.clamp(1, daysInMonth(year, month));