Home > Blockchain >  How to get the first, second, third, and fourth week of the month?
How to get the first, second, third, and fourth week of the month?

Time:02-11

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!

CodePudding user response:

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));
  • Related