How to set start of the week as Sunday and end as Saturday in Dart?

Viewed 108

I can get start of the week as Monday using method below:

DateTime findFirstDateOfTheWeek(DateTime date) {
    return date.subtract(Duration(days: date.weekday - 1));
  }

and end of the week, the Sunday, as:

DateTime findLastDateOfTheWeek(DateTime date) {
    return date.add(Duration(days: DateTime.daysPerWeek - date.weekday));
  }

Now the requirements are, to treat Sunday as week start and Saturday as week end. I tried tweaking above method but could not get it working. Any help would be appreciated. Thanks

1 Answers

Since DateTime.weekday counts from 1 (Monday) to 7 (Sunday):

date.subtract(Duration(days: date.weekday - 1))

will give us the date of the start of the week using what DateTime considers to be the first day of the week (Monday). To treat Sunday as the first day of the week instead, we can try to get the previous day from that:

date.subtract(Duration(days: date.weekday - 1)).subtract(const Duration(days: 1))

The above is algebraically equivalent to date - (weekday - 1) - 1, which can be simplified to just date - weekday. But that's not quite right because weekday ranges from [1, 7], and we never want to subtract 7 days. In that case, we want to subtract 0. The modulus operator handles that nicely, ultimately giving us:

DateTime findFirstDateOfTheWeek(DateTime date) {
  return date.subtract(Duration(days: date.weekday % DateTime.daysPerWeek));
}

To get the last day of the week where Saturday is treated as the last day of the week, you can just get the first day of the week and add 6 days:

DateTime findLastDateOfTheWeek(DateTime date) {
  return findFirstDateOfTheWeek(date).add(
    const Duration(days: DateTime.daysPerWeek - 1));
}
Related