Dart/Flutter get first DateTime of this week

4,537

Solution 1

If Sunday is your first day of week.

var d = DateTime.now();
var weekDay = d.weekday;
var firstDayOfWeek = d.subtract(Duration(days: weekDay));

According to Flutter docs weekDay returns

The day of the week [monday]..[sunday].

  • In accordance with ISO 8601
  • a week starts with Monday, which has the value 1.

if Monday is first day of week then

var firstDayOfWeek = d.subtract(Duration(days: weekDay - 1));

Solution 2

For Sunday:

DateTime today = DateTime.now();
DateTime _firstDayOfTheweek =
        today.subtract(new Duration(days: today.weekday));
print(_firstDayOfTheweek.day);

For Monday:

DateTime _firstDayOfTheweek =
        today.subtract(new Duration(days: today.weekday - 1));
print(_firstDayOfTheweek.day);

For Saturday:

DateTime _firstDayOfTheweek =
        today.subtract(new Duration(days: today.weekday + 1));
print(_firstDayOfTheweek.day);

Solution 3

The DateTime class stores int constants for the day of the week which you could use to calculate the start date you need. Something like this should work:

void main() {
  var startOfWeek = DateTime.saturday;
  var currentDate = DateTime.now();
  var daysSince = currentDate.weekday + (DateTime.sunday - startOfWeek);

  var result = currentDate.subtract(Duration(days: daysSince));

  print('Date at start of week is $result');
}
Share:
4,537
shababhsiddique
Author by

shababhsiddique

U S.O. much

Updated on December 22, 2022

Comments

  • shababhsiddique
    shababhsiddique over 1 year

    Using flutter on android I am trying to get the first date of current week. For example today is 13/7/2020, assuming week starts from Saturday the first date of current week will be 11/7/2020.

    This for example to get first date of month

    DateTime firstDay = new DateTime(
      DateTime.now().year,
      DateTime.now().month,
      1,
    ); //get first date this month
    

    The end goal is to get timestamp of that date and fetch entries from sqflite database that is higher than that.