toDateInYear method

  1. @useResult
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

@useResult
DateTime? toDateInYear(int setYear) {
  if (month == DateTime.february && day == DateConstants.daysInFebLeapYear) {
    final bool isTargetLeap = DateTimeUtils.isLeapYear(year: setYear);
    if (!isTargetLeap) {
      return null;
    }
  }

  return DateTime(
    setYear,
    month,
    day,
    hour,
    minute,
    second,
    millisecond,
    microsecond,
  );
}