I am trying to get date range for a particular week number.

Following is my code to get week number with respect to current date

final date = DateTime.now();
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();

if (daysInFirstWeek > 3) {
  weeks += 1;
}
print("Week Range $weeks");

What I don't understand is how I get start and end date for a particular week number.

Any help would be appreciated.

2 Answers

1
user603749 On Best Solutions

Assuming your week is zero based, you need to do something like this:

final date = new DateTime.now();
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();


main(){
  int week = weeks;
  print("Start Date for week $week: ${startOfYear.add(Duration(days: 7*week))}");
  print("End Date for week $week: ${startOfYear.add(Duration(days: 7*week+6))}");
}
0
Nadeem Siddique On

To get the starting and day of week from week number and year.

DateTime getDateByWeekNumber({
  int weeknumber,
  int year,
  bool start
}) {
  //check if start == true retrun start date of week
  //else return end date
  var days = ((weeknumber - 1) * 7) + (start ? 0 : 6);
  return DateTime.utc(year, 1, days);
}

This is in accordance to ISO 8601. You can very week number here