Start by figuring out how to find how many days there are from a given weekday to the Monday on or after that day. Examples help; if the given weekday is:
- Monday, add 0 days.
- Tuesday, add 6 days.
- Wednesday, add 5 days.
- ... etc. ...
- Sunday, add 1 day.
We could make a lookup table, but we also can devise that the offset (in days) from a given weekday to the Monday on or after that day has the form (7 - x) % 7
where x
corresponds to the given weekday. We'd want that value to be 0 for Monday, 1 for Tuesday, and so on, until 6 for Sunday. Dart's DateTime.weekday
uses values 1 (DateTime.monday
) through 7 (DateTime.sunday
), so we can easily map that to the value we want via DateTime.weekday - DateTime.monday
.
Once we compute that offset, we can find the first day of the current month, add that offset to find the first Monday of the month, and then you can iteratively add 7 days until you reach the next month, and we can use DateFormat
from package:intl
to format the dates the way you want:
import 'package:intl/intl.dart';
String formatDate(DateTime dateTime) => DateFormat('dd MMM').format(dateTime);
void main() {
var now = DateTime.now();
var firstOfMonth = DateTime(now.year, now.month, 1);
var firstMonday =
firstOfMonth.addCalendarDays((7 - (firstOfMonth.weekday - DateTime.monday)) % 7);
var currentMonday = firstMonday;
while (currentMonday.month == now.month) {
var nextMonday = currentMonday.addCalendarDays(7);
var nextSunday = nextMonday.addCalendarDays(-1);
print('${formatDate(currentMonday)} - ${formatDate(nextSunday)}');
currentMonday = nextMonday;
}
}
See https://stackoverflow.com/a/68216029/ for the implementation of the addCalendarDays
extension method.