【发布时间】:2023-02-19 07:44:09
【问题描述】:
我想知道如何获得给定周数的日期。例如: 如果我的当前周数是 2021 年的第 52 周,那么我想知道第 52 周是哪几天。 我怎样才能用颤动得到这个?
【问题讨论】:
-
谢谢你的回答。但实际上,我想要特定周数的天数。这些显示了如何确定当年的周数。
我想知道如何获得给定周数的日期。例如: 如果我的当前周数是 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()}';
}
}
【讨论】: