lastDayOfWeek property

DateTime lastDayOfWeek

Returns a DateTime instance representing the last day of the week of this DateTime.

Example:

DateTime currentDate = DateTime(2022, 1, 8);
DateTime lastDayOfWeek = currentDate.lastDayOfWeek;
print(lastDayOfWeek);  // Output: 2022-01-09 12:00:00.000 (Assuming Sunday is the last day of the week)

The lastDayOfWeek getter returns a new DateTime instance with the same year, month, and hour as the original date but adjusted to the last day of the week. Daylight Saving Time is handled by setting the hour to 12:00 Noon rather than the default of Midnight (00:00:00). The week in this context is considered to end on Sunday.

Implementation

DateTime get lastDayOfWeek {
  /// Handle Daylight Savings by setting hour to 12:00 Noon
  /// rather than the default of Midnight
  final day = DateTime.utc(year, month, this.day, 12);

  /// Weekday is on a 1-7 scale Monday - Sunday,
  var increaseNum = (7 - day.weekday) % 7;
  return day.add(Duration(days: 7 - increaseNum));
}