getDateTimeEndOf function

DateTime? getDateTimeEndOf(
  1. DateTime time,
  2. Object? unit, {
  3. DateTimeWeekDay? weekFirstDay,
  4. String? locale,
})

Returns the end of a time unit using time as reference.

weekFirstDay the desired first day of week for computation behavior. locale Locale code to use if weekFirstDay is null and need to be defined.

Implementation

DateTime? getDateTimeEndOf(DateTime time, Object? unit,
    {DateTimeWeekDay? weekFirstDay, String? locale}) {
  var unitParsed = parseUnit(unit);
  if (unitParsed == null) return null;

  switch (unitParsed) {
    case Unit.years:
      return DateTime(time.year, 12, 31, 23, 59, 59, 999);
    case Unit.quarters:
      return getDateTimeThisMonth(getDateTimeStartOf(time, unitParsed)).b;
    case Unit.weeks:
      {
        weekFirstDay ??= getWeekFirstDay(locale);
        var dateTimeRange =
            getDateTimeRange(DateRangeType.thisWeek, time, weekFirstDay);
        return dateTimeRange.b;
      }
    case Unit.months:
      return getDateTimeThisMonth(DateTime(time.year, time.month, 1)).b;
    case Unit.days:
      return DateTime(time.year, time.month, time.day, 23, 59, 59, 999);
    case Unit.hours:
      return DateTime(time.year, time.month, time.day, time.hour, 59, 59, 999);
    case Unit.minutes:
      return DateTime(
          time.year, time.month, time.day, time.hour, time.minute, 59, 999);
    case Unit.seconds:
      return DateTime(time.year, time.month, time.day, time.hour, time.minute,
          time.second, 999);
    default:
      break;
  }

  if ('$unit'.toLowerCase().trim() == 'date') {
    var startOf = getDateTimeStartOf(time, unit)!;
    return startOf
        .add(Duration(hours: 23, minutes: 59, seconds: 59, milliseconds: 999));
  }

  throw ArgumentError("Can't handle unit: $unit");
}