toDateInYear method

DateTime? toDateInYear(
  1. int setYear
)

Ignores the year of the current DateTime and returns a new DateTime with the specified setYear.

Requires month and day to be set in the current DateTime.

Returns null if the date is invalid in setYear — for example, when this is February 29 (a leap day) and setYear is not a leap year.

Implementation

DateTime? toDateInYear(int setYear) {
  // Guard: Feb 29 only exists in leap years.
  if (month == DateTime.february && day == 29) {
    final bool targetIsLeap = setYear % 4 == 0 && (setYear % 100 != 0 || setYear % 400 == 0);
    if (!targetIsLeap) return null;
  }
  return DateTime(setYear, month, day, hour, minute, second, millisecond, microsecond);
}