在flutter中获取给定周数的日期



我想知道如何获得给定周数的日期。例如:如果我现在的周数是2021年的52,那么我想知道第52周的哪几天。我怎么能用颤动得到这个?

不确定Flutter中是否有类似的东西。

所以这里有一个长期的解决方案。考虑到我们已经度过了这一年;

第1步:你可以将数字除以4并将其降为地板。这将给你一个月的时间。

步骤2:然后您可以从计算的月份和4的倍数中减去给定的数字。这将给你一个月中的星期。

第3步:现在,您可以用一天中的一周乘以7。这会给你一天的时间。

第4步:现在您只需使用DateTime().day即可获得该周的开始日期,然后继续。

下面是一个工作示例:

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.

我不知道这是否仍然需要,但我遇到了必须解决的相同问题。这真的与Flutter无关——这是Dart唯一的问题。

以下是我的解决方案:注意:我测试了几次约会/几周,结果似乎很好。

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对象定义为:

class WeekDates {
WeekDates({
required this.from,
required this.to,
});
final DateTime from;
final DateTime to;
@override
String toString() {
return '${from.toIso8601String()} - ${to.toIso8601String()}';
}
}

最新更新