我正在尝试在特定的日期创建一个倒计时,并显示到那时还剩下多少小时,分钟和秒。
例如我想将柜台日期设置为:2018年10月25日星期四上午7:14:05
我想为用户显示..剩余时间:hh:mm:ss直到10月25日…
我尝试了这个:
@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(); }
但是结果是:03:25:40 ..这真的不是真的…
这该怎么做?
首先-存在错误:您必须使用data.remaining.inMilliseconds而不是data.remaining.inSeconds
data.remaining.inMilliseconds
data.remaining.inSeconds
对于格式化,最好使用Duration而不是DateTime。但是您可以更改现有代码,例如:
var format = new DateFormat("mm:ss"); var dateString = '${data.remaining.inHours}:${format.format(DateTime.fromMillisecondsSinceEpoch(data.remaining.inMilliseconds))}; print(dateString);
UPD 小工具,用于显示剩余时间
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),); });