stacktrace2234
stacktrace2234

Reputation: 179

Flutter: get first day of the week and last day of the week?

I would like to make some pagination that holds the records that are on the same week.

So the interval will be between monday 00:00 - sunday 23:59

All this in unix time. So I can query the database the records that are between this interval.

Upvotes: 0

Views: 1412

Answers (2)

Ash Khachatryan
Ash Khachatryan

Reputation: 455

This week first day is

DateTime firstDayOfCurrentWeek() {
    DateTime now = DateTime.now();
    DateTime firstDayOfCurrentWeek =
        now.subtract(Duration(days: now.weekday - 1));
    return firstDayOfCurrentWeek.clearTime();
  }


  DateTime clearTime() {
    return DateTime(this.year, this.month, this.day, 0, 0, 0, 0, 0);
  }

Upvotes: -1

loyal
loyal

Reputation: 257

You can use DateTime.

DateTime now = DateTime.now();    

int daysOfWeek = now.weekday - 1;
DateTime firstDay = DateTime(now.year, now.month, now.day - daysOfWeek);
DateTime lastDay = firstDay.add(Duration(days: 6, hours: 23, minutes: 59));

print(firstDay);
print(lastDay);

DateTime nextFirst = firstDay.add(Duration(days: 7));
DateTime nextLast = lastDay.add(Duration(days: 7));

print(nextFirst);
print(nextLast);

DateTime prevFirst = firstDay.subtract(Duration(days: 7));
DateTime prevLast = lastDay.subtract(Duration(days: 7));

print(prevFirst);
print(prevLast);

Upvotes: 0

Related Questions