Search code examples
dartcountdowntimer

Dart : Show the time until the next time


How to show a countdown time duration until the next alarm

Code:

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);
}

But the time difference is wrong and it doesn't animate. Also how to make sure the time difference works when it's the same day and time of the next day i.e. now is Dec 1 2:30 PM and I want to get the difference on Dec 2 6:15 AM.


Solution

  • It does not work because TimeOfDay represents a time during the day, independent of the date that day might fall on or the time zone. The time is represented only by hour and minute.

    If you want a countdown that spans multiple days a DateTime must be used and the time difference evaluation needs some math before formatting the result string, something like:

    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(':');
    }