Dart 获取下周五的日期

Dart get date of next friday

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

解决方案

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

我对上面的代码做了一些小的调整(答案由 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,
        ),
      );
    }
  }
}