lastDayOfWeek method
Returns a DateTime representing the last day of the week for this DateTime.
startOfWeek is an optional parameter specifying the weekday that is considered
the start of the week (1 for Monday, 7 for Sunday, etc.). Defaults to Monday.
Preserves the original time zone: UTC stays UTC, local stays local.
Implementation
DateTime lastDayOfWeek({int startOfWeek = DateTime.monday}) {
final normalizedStartOfWeek =
((startOfWeek - 1) % DateTime.daysPerWeek) + 1;
final daysToAdd =
(DateTime.daysPerWeek - weekday + normalizedStartOfWeek - 1) %
DateTime.daysPerWeek;
// Convert to UTC and then back to the original timezone to ensure correct midnight
final utcLastDayOfWeek = toUtc().add(Duration(days: daysToAdd));
return isUtc ? utcLastDayOfWeek : utcLastDayOfWeek.toLocal();
}