0

I would like to know how can I get the dates of the given week number. For example: If I have the present week number is 52 in 2021, then I want to know which are the days in week 52. How can I get this with flutter?

samin
  • 482
  • 5
  • 9

2 Answers2

0

Not sure if there's something like that in Flutter.

So here's a long solution. Considering we already have the year;

Step 1: You can divide the number by 4 and floor it. Which will give you the month.

Step 2: Then you can subtract the given number from the multiple of the calculated month and 4. Which will give you the week of the month.

Step 3: Now for the day, you can multiple 7 with the week of the month. which will give you the day.

Step 4: Now you can just use DateTime().day to get the starting day of that week and continue from there.

Here's a working example:

week = 13
Step 1: 13/4 = 3.25. => 3rd month
Step 2: 3*4 = 12 
        13-12 = 1 => 1st week of the month
Step 3: 7*1 => 7th day of the month
Step 4: DateTime(2021, 3, 7).day // output: 7 which means Sunday.
aki
  • 78
  • 8
0

I don't know if this is still required, but I encountered the same problem I had to resolve. It really has nothing to do with Flutter - this is Dart's only problem.

Here is my solution: Note: I tested for a couple of dates/weeks and it seemed to work fine.

WeekDates getDatesFromWeekNumber(int year, int weekNumber) {
  // first day of the year
  final DateTime firstDayOfYear = DateTime.utc(year, 1, 1);

  // first day of the year weekday (Monday, Tuesday, etc...)
  final int firstDayOfWeek = firstDayOfYear.weekday;

  // Calculate the number of days to the first day of the week (an offset)
  final int daysToFirstWeek = (8 - firstDayOfWeek) % 7;

  // Get the date of the first day of the week
  final DateTime firstDayOfGivenWeek = firstDayOfYear
      .add(Duration(days: daysToFirstWeek + (weekNumber - 1) * 7));

  // Get the last date of the week
  final DateTime lastDayOfGivenWeek =
      firstDayOfGivenWeek.add(Duration(days: 6));

  // Return a WeekDates object containing the first and last days of the week
  return WeekDates(from: firstDayOfGivenWeek, to: lastDayOfGivenWeek);
}

WeekDates object is defined as:

class WeekDates {
  WeekDates({
    required this.from,
    required this.to,
  });

  final DateTime from;

  final DateTime to;

  @override
  String toString() {
    return '${from.toIso8601String()} - ${to.toIso8601String()}';
  }
}
Nodios
  • 439
  • 6
  • 18