Search code examples
flutterdarttimercountdown

Daily automatic countdown


At a specified moment of 4:30 pm every day, I want to create an automatic daily countdown timer. The timer displays + one day in the countdown after midnight in the following code, which breaks on the last day of the month.

For Example, Everyday a new content will be released at 4:30 pm. Countdown should Start Time is 4:31 pm and end time should be 4:30pm.

Problem: The clock is advancing by one day. To Emaple: 01 days, 22 hr 33 min 23 s. Additionally, the timer indicates that time has expired if the month date is 30 or 31.

The code is is follows

/// Date and Time for Countdown
final int _countdownTime = DateTime(
  DateTime.now().year,
  DateTime.now().month,
  DateTime.now().add(const Duration(hours: 12)).day,
  16,
  30,
).millisecondsSinceEpoch;

/// Countdown Widget
CountdownTimer(
     endTime: _countdownTime,
     textStyle: TextStyle(
     fontSize: 18.0,
     color: Colors.grey.shade700,
                         ),
                            ),

Solution

  • Your main problem is that you are changing only one component of the date, but expect the rest to stay the same. That is not how dates work. If you add 12 hours to 15:20 on Friday, the result is not 27:20 on Friday. It's 03:20 on Saturday. So adding only to the hours without taking into account the full date is failing for many samples.

    So if you play around with dates, never dissect them and play around with parts. All the parts are connected and dependent. If you add a second to 23:59:59 on 12/31, even the year will change. So don't reinvent the wheel on any of that, always change the complete date, never just parts of it:

    DateTime getNextDeadline(DateTime now) {
      final todaysDeadline = DateTime(
        now.year,
        now.month,
        now.day,
        16,
        30);
      
      if(now.isBefore(todaysDeadline)) {
        return todaysDeadline;
      }
         
      return todaysDeadline.add(Duration(days: 1));
    }
    
    void main() {
      final date = DateTime.now();
      
      final nextDeadline = getNextDeadline(date);
        
      print(nextDeadline);
    }