getDateTimeStartOf function

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

Returns the start 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? getDateTimeStartOf(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);
    case Unit.quarters:
      return DateTime(time.year, (time.month ~/ 3) * 3);
    case Unit.weeks:
      {
        weekFirstDay ??= getWeekFirstDay(locale);
        var dateTimeRange =
            getDateTimeRange(DateRangeType.thisWeek, time, weekFirstDay);
        return dateTimeRange.a;
      }
    case Unit.months:
      return DateTime(time.year, time.month);
    case Unit.days:
      return DateTime(time.year, time.month, time.day);
    case Unit.hours:
      return DateTime(time.year, time.month, time.day, time.hour);
    case Unit.minutes:
      return DateTime(time.year, time.month, time.day, time.hour, time.minute);
    case Unit.seconds:
      return DateTime(
          time.year, time.month, time.day, time.hour, time.minute, time.second);
    default:
      break;
  }

  if ('$unit'.toLowerCase().trim() == 'date') {
    return DateTime(time.year, time.month, time.day);
  }

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