我正在尝试获取特定星期数的日期范围。
以下是我的代码以获取相对于当前日期的星期数
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");
我不了解我如何获取特定星期数的开始日期和结束日期。
任何帮助将不胜感激。
答案 0 :(得分:1)
假设您的一周是从零开始的,则需要执行以下操作:
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))}");
}
答案 1 :(得分:0)
要从星期数和年份中获取星期几和星期几。
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);
}
这符合ISO8601。您可以非常方便地选择星期几here