Dart 获取下周五的日期

Sim*_*mon 4 date countdown dart

我正在尝试制作一个应用程序来倒计时直到下周五,但因此我需要下周五的日期。非常感谢任何帮助!

小智 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


Sha*_*ton 6

我对上面的代码添加了一些细微的调整(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)

  • 这是一个简洁的替代方案:`Duration(days: day == weekday ? 7 : (day - weekday) % DateTime.daysPerWeek),` (2认同)