我正在尝试制作一个倒计时到下一个星期五的时间的应用程序,但是我需要下一个星期五的日期。 任何帮助深表感谢!
答案 0 :(得分:3)
extension DateTimeExtension on DateTime {
DateTime next(int day) {
return this.add(
Duration(
days: (day - this.weekday) % DateTime.daysPerWeek,
),
);
}
}
void main() {
var today = DateTime.now();
print(today);
print(today.next(DateTime.friday));
print(today.next(DateTime.friday).weekday == DateTime.friday);
// Works as expected when the next day is after sunday
print(today.next(DateTime.monday));
print(today.next(DateTime.monday).weekday == DateTime.monday);
}
2020-06-24 18:47:40.318
2020-06-26 18:47:40.318
true
2020-06-29 18:47:40.318
true
有关DateTime
的更多信息,请参见this。
答案 1 :(得分:1)
我对上面的代码做了一些小调整(davideliseo 发布的答案)
上面的代码有一个问题,它找不到下一周的那一天,但返回了传递给函数的那一天。
例如:我的 DateTime 是星期六。我希望日历中的下一个星期六返回而不是开始的那个星期六。
另外,我包含了一个以前的函数,因为它可能会有所帮助。
extension DateTimeExtension on DateTime {
DateTime next(int day) {
if (day == this.weekday)
return this.add(Duration(days: 7));
else {
return this.add(
Duration(
days: (day - this.weekday) % DateTime.daysPerWeek,
),
);
}
}
DateTime previous(int day) {
if (day == this.weekday)
return this.subtract(Duration(days: 7));
else {
return this.subtract(
Duration(
days: (this.weekday - day) % DateTime.daysPerWeek,
),
);
}
}
}