4

I want to get all four weeks (first and last day date) on the current month with Monday as the start of the week.

I can only figure out how to get the current week's first and last date with this code:

var firstDayOfTheWeek =  DateTime.now().subtract(Duration(days: DateTime.now().weekday - 1));
var lastDayOfTheWeek =  DateTime.now().add(Duration(days: DateTime.daysPerWeek - DateTime.now().weekday));

Thanks in advance!

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Does this answer your question? [print first monday of every week of current month Flutter/Dart](https://stackoverflow.com/questions/67183678/print-first-monday-of-every-week-of-current-month-flutter-dart) – nvoigt Feb 09 '22 at 06:47

1 Answers1

2

Below method return next weekday's DateTime what you want from now or specific day.

DateTime getNextWeekDay(int weekDay, {DateTime from}) {
  DateTime now = DateTime.now();

  if (from != null) {
    now = from;
  }

  int remainDays = weekDay - now.weekday + 7;

  return now.add(Duration(days: remainDays));
}

The weekday parameter can be came like below DateTime const value or just int value.

class DateTime {
...
  static const int monday = 1;
  static const int tuesday = 2;
  static const int wednesday = 3;
  static const int thursday = 4;
  static const int friday = 5;
  static const int saturday = 6;
  static const int sunday = 7;
...
}

If you want to get next Monday from now, call like below.

DateTime nextMonday = getNextWeekDay(DateTime.monday);

If you want to get next next Monday from now, call like below.
Or you just add 7 days to 'nextMonday' variable.

DateTime nextMonday = getNextWeekDay(DateTime.monday);


DateTime nextNextMonday = getNextWeekDay(DateTime.monday, from: nextMonday);
or
DateTime nextNextMonday = nextMonday.add(Duration(days: 7));
KuKu
  • 6,654
  • 1
  • 13
  • 25