Dart:显示时间到下一次

Dart : Show the time until the next time

如何显示下一个闹钟的倒计时持续时间

代码:

TimeOfDay _nextSalah(List<SalahModel> salahs) {
    DateTime now = DateTime.now();
    List<TimeOfDay> times = [];
    int currentSalah;

    salahs.forEach((s) => times.add(s.time));
    times.add(TimeOfDay(hour: now.hour, minute: now.minute));
    times.sort((a, b) => a.hour.compareTo(b.hour));
    currentSalah = times.indexWhere((time) => time.hour == now.hour);

    return TimeOfDay(hour: times[currentSalah].hour, minute: times[currentSalah].minute);
}

但是时差不对,没有动画。另外如何确保时差在同一天和第二天的时间时有效,即现在是 12 月 1 日 2:30 下午,我想在 12 月 2 日 6:15 上午获得时差。

它不起作用,因为 TimeOfDay 表示一天中的某个时间,与当天可能落在的日期或时区无关。时间仅由小时和分钟表示。

如果您想要跨越多天的倒计时,则必须使用 DateTime 并且时差评估在格式化结果字符串之前需要一些数学运算,例如:

String nextTime(DateTime nextAlarmTime) {
  List<int> ctime = [0, 0, 0, 0];
  DateTime now = DateTime.now();
  int diff = nextAlarmTime.difference(now).inSeconds;
  ctime[0] = diff ~/ (24 * 60 * 60); // days
  diff -= ctime[0] * 24 * 60 * 60;

  ctime[1] = diff ~/ (60 * 60); // hours
  diff -= ctime[1] * 60 * 60;

  ctime[2] = diff ~/ 60; // minutes
  ctime[3] = diff - ctime[2] * 60;  // seconds

  return ctime.map((val) => val.toString().padLeft(2, '0')).join(':');
}