如何获取该月的第一、二、三、四周?

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

我想获取当月所有四个星期(第一天和最后一天的日期),星期一作为一周的开始。

我只能弄清楚如何使用此代码获取本周的第一个和最后一个日期:

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

提前致谢!

下面的方法 return 下一个工作日的日期时间你想要从现在或特定日期开始。

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));
}

weekday 参数可以像下面的 DateTime const 值或只是 int 值。

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;
...
}

如果你想从现在开始下周一得到,请像下面这样打电话。

DateTime nextMonday = getNextWeekDay(DateTime.monday);

如果你想从现在开始下个星期一得到,请按下面的方式打电话。
或者您只需将 7 天添加到 'nextMonday' 变量。

DateTime nextMonday = getNextWeekDay(DateTime.monday);


DateTime nextNextMonday = getNextWeekDay(DateTime.monday, from: nextMonday);
or
DateTime nextNextMonday = nextMonday.add(Duration(days: 7));