简体   繁体   中英

Countdown timer date and time format in Flutter

I'm making a Countdown timer, but the problem is, how can I make it realize the difference from AM to PM if it is a 24h clock? For instance, I have put the wakeUpTime inside the code to be tomorrow morning at 10. And if the time I'm asking this question is let's say 17:55h, I get a countdown to only 4 hours and 5min remaining, but it is supposed to say 16hours and 5min left. How can I achieve this? Here is the code below:

DateTime formatedDate = DateTime.parse(wakeUpTime);
int estimatedTimeLeft = formatedDate.millisecondsSinceEpoch; // needed date to countdown to


StreamBuilder(
                      stream: Stream.periodic(Duration(seconds: 1), (i) => i),
                      builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                        DateFormat format = DateFormat("hh:mm:ss");
                        int timeNow= DateTime
                            .now()
                            .millisecondsSinceEpoch;
                        Duration remaining = Duration(milliseconds: estimatedTimeLeft - timeNow);
                        var dateString = '${remaining.inHours}:${format.format(
                            DateTime.fromMillisecondsSinceEpoch(remaining.inMilliseconds))}';
                        print(dateString);
                        return Container(
                          child: Text(dateString),);
                      });

Did I format the Date and time wrong, or is it something else?

Thanks in advance for your help!

Below is a minimal code for testing, you can just copy and paste the code below, should work fine. Just input the endDate in DateTime format.


import 'dart:async';
import 'package:flutter/material.dart';

class DebugErrorClass extends StatefulWidget {
  DebugErrorClass({
    Key? key,
  }) : super(key: key);

  @override
  _DebugErrorClassState createState() => _DebugErrorClassState();
}

class _DebugErrorClassState extends State<DebugErrorClass> {
  String remainingTime = "";
  Timer? _timer;
  StreamController<String> timerStream = StreamController<String>.broadcast();
  final endDate = DateTime.now().add(Duration(days: 5)); // the date, time u set
  final currentDate = DateTime.now();

  @override
  void initState() {
    prepareData();
    super.initState();
  }

  @override
  void dispose() {
    try{
      if (_timer != null && _timer!.isActive) _timer!.cancel();
    }catch(e){
      print(e);
    }
    super.dispose();
  }

  prepareData(){
    final difference = daysBetween(currentDate, endDate);
    print(difference);
    print('difference in days');
    // get remaining time in second
    var result = Duration(seconds: 0);
    result = endDate.difference(currentDate);
    remainingTime = result.inSeconds.toString(); // convert to second
//    remainingTime = '10'; // change this value to test for min function
  }

  int daysBetween(DateTime from, DateTime to) {
    from = DateTime(from.year, from.month, from.day);
    to = DateTime(to.year, to.month, to.day);
    return (to.difference(from).inHours / 24).round();
  }

  String dayHourMinuteSecondFunction(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String days = twoDigits(duration.inDays);
    String twoDigitHours = twoDigits(duration.inHours.remainder(24));
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return days+' '+"Days"+' '+twoDigitHours+' '+"Hours"+' '+twoDigitMinutes+' '+"Minutes"+' '+twoDigitSeconds+"Seconds";
  }

  Widget dateWidget(){
    return StreamBuilder<String>(
        stream: timerStream.stream,
        initialData: "0",
        builder: (cxt, snapshot) {
          const oneSec = Duration(seconds: 1);
          if (_timer != null && _timer!.isActive) _timer!.cancel();
          _timer = Timer.periodic(oneSec, (Timer timer) {
            try {
              int second = int.tryParse(remainingTime)?? 0;
              second = second - 1;
              if (second < -1) return;
              remainingTime = second.toString();
              if (second == -1) {
                timer.cancel();
                print('timer cancelled');
              }
              if(second >= 0){
                timerStream.add(remainingTime);
              }
            } catch (e) {
              print(e);
            }
          });
          String remainTimeDisplay = "-";
          try {
              int seconds = int.parse(remainingTime);
              var now = Duration(seconds: seconds);
              remainTimeDisplay = dayHourMinuteSecondFunction(now);
          } catch (e) {
            print(e);
          }
          print(remainTimeDisplay);
          return Text(remainTimeDisplay, textAlign: TextAlign.center,);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          alignment: Alignment.center,
          width: double.infinity,
          height: double.infinity,
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                dateWidget(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM