小智 13
extension DateTimeExtension on DateTime {
DateTime next(int day) {
return this.add(
Duration(
days: (day - this.weekday) % DateTime.daysPerWeek,
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
2020-06-24 18:47:40.318
2020-06-26 18:47:40.318
true
2020-06-29 18:47:40.318
true
Run Code Online (Sandbox Code Playgroud)
有关 的更多信息,请参阅此内容DateTime。
我对上面的代码添加了一些细微的调整(davideliseo 发布的答案)
上面的代码有一个问题,它无法找到下一周的日期,但返回了传递给函数的日期。
示例:我的日期时间是星期六。我希望日历中的下一个星期六返回的不是开始时的同一个星期六。
另外,我还包含了以前的功能,因为它可能会有所帮助。
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,
),
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2774 次 |
| 最近记录: |