Flutter 中的倒数计时器日期和时间格式

Posted

技术标签:

【中文标题】Flutter 中的倒数计时器日期和时间格式【英文标题】:Countdown timer date and time format in Flutter 【发布时间】:2022-01-05 18:20:35 【问题描述】:

我正在制作一个倒数计时器,但问题是,如果它是 24 小时制时钟,我如何让它实现从上午到下午的区别?例如,我将wakeUpTime 放入代码中,明天早上 10 点。如果我问这个问题的时间是 17:55,我会倒计时只剩下 4 小时 5 分钟,但是应该说还有16小时5分钟。我怎样才能做到这一点?下面是代码:

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

我的日期和时间格式是否错误,还是其他原因?

提前感谢您的帮助!

【问题讨论】:

你传递的wakeUpTime是什么? @HeIsDying wakeUpTime : 2021-11-28T21:09:44 【参考方案1】:

下面是一个最小的测试代码,你可以复制并粘贴下面的代码,应该可以正常工作。只需输入 DateTime 格式的 endDate。


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(),
              ],
            ),
          ),
        ),
      ),
    );
  

【讨论】:

以上是关于Flutter 中的倒数计时器日期和时间格式的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:当倒数计时器达到 0 时执行动作

动态 Python 倒数计时器

颤振倒数计时器

具有可配置开始时间的 JQuery 倒数计时器

如何在android的状态栏上显示倒数计时器,如时间显示?

React 中的倒数计时器