endOf method

DateTime endOf(
  1. DurationUnit unit
)

Returned object will have same timezone as this

Notes:

  • instance.startOf(DurationUnit.week) will throw MomentException

  • instance.startOf(DurationUnit.microsecond) will return clone of that instance

Implementation

DateTime endOf(DurationUnit unit) {
  switch (unit) {
    case DurationUnit.microsecond:
      return clone();
    case DurationUnit.week:
      throw MomentException(
          "endOf(DurationUnit.week) is not supported on DateTime object. You can use it on Moment objects");
    case DurationUnit.millisecond:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        month,
        day,
        hour,
        minute,
        second,
        millisecond,
        999,
      );
    case DurationUnit.second:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        month,
        day,
        hour,
        minute,
        second,
        999,
        999,
      );
    case DurationUnit.minute:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        month,
        day,
        hour,
        minute,
        59,
        999,
        999,
      );
    case DurationUnit.hour:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        month,
        day,
        hour,
        59,
        59,
        999,
        999,
      );
    case DurationUnit.day:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        month,
        day,
        23,
        59,
        59,
        999,
        999,
      );
    case DurationUnit.month:
      const daysInMonths = [
        0,
        31,
        28,
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31
      ];

      final bool extraFebDay = month == DateTime.february && isLeapYear;
      return DateTime(
        year,
        month,
        daysInMonths[month] + (extraFebDay ? 1 : 0),
        23,
        59,
        59,
        999,
        999,
      );
    case DurationUnit.year:
      return DateTimeConstructors.withTimezone(
        isUtc,
        year,
        12,
        31,
        23,
        59,
        59,
        999,
        999,
      );
  }
}