Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date countdown in dart

Tags:

flutter

dart

am trying to create a countdown on specific date i have and display how many hours, minutes and seconds left until then ..

for example i want to set the counter date to: Thursday, October 25, 2018 7:14:05 AM

and i want to display for the user.. remaining time: hh:mm:ss till 25 october ...

i tried this:

@override
void initState() {

new CountdownTimer(new Duration(milliseconds: 1540451645), new Duration(seconds: 1)).listen((data) {
  print('Remaining time: ${data.remaining.inSeconds}');
  print(new DateTime.now().millisecondsSinceEpoch);
  print(DateTime.fromMillisecondsSinceEpoch(data.remaining.inSeconds));
  var format = new DateFormat("hh:mm:ss");
  var dateString = format.format(DateTime.fromMillisecondsSinceEpoch(data.remaining.inSeconds));
  print(dateString);
});
super.initState();
}

but the result is: 03:25:40.. which is really not true ...

how to do this?

like image 343
lamatat Avatar asked Dec 18 '22 20:12

lamatat


1 Answers

First of all - there is error: you have to use data.remaining.inMilliseconds instead of data.remaining.inSeconds

For formatting it'll be better to use Duration instead of DateTime. But you can change your existing code like:

var format = new DateFormat("mm:ss");
var dateString = '${data.remaining.inHours}:${format.format(DateTime.fromMillisecondsSinceEpoch(data.remaining.inMilliseconds))};
print(dateString);

UPD Widget for showing remaining time

int estimateTs = DateTime(2018, 11, 5, 7, 15, 30).millisecondsSinceEpoch; // set needed date

....

StreamBuilder(
                      stream: Stream.periodic(Duration(seconds: 1), (i) => i),
                      builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                        DateFormat format = DateFormat("mm:ss");
                        int now = DateTime
                            .now()
                            .millisecondsSinceEpoch;
                        Duration remaining = Duration(milliseconds: estimateTs - now);
                        var dateString = '${remaining.inHours}:${format.format(
                            DateTime.fromMillisecondsSinceEpoch(remaining.inMilliseconds))}';
                        print(dateString);
                        return Container(color: Colors.greenAccent.withOpacity(0.3),
                          alignment: Alignment.center,
                          child: Text(dateString),);
                      });
like image 142
Andrey Turkovsky Avatar answered Feb 07 '23 15:02

Andrey Turkovsky