firstDayOfWeek method
Returns a DateTime representing the first 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.
Implementation
DateTime firstDayOfWeek({int startOfWeek = DateTime.monday}) {
// Normalize the startOfWeek value to be within the range of 1-7
final normalizedStartOfWeek =
((startOfWeek - 1) % DateTime.daysPerWeek) + 1;
// Calculate the difference between the current weekday and normalizedStartOfWeek
// and adjust it to be positive and within the range of 0-6
final daysToSubtract =
(weekday - normalizedStartOfWeek + DateTime.daysPerWeek) %
DateTime.daysPerWeek;
return subtract(Duration(days: daysToSubtract));
}