【问题标题】:How can I get the difference between 2 times?我怎样才能得到2次之间的差异?
【发布时间】:2020-06-07 07:15:27
【问题描述】:

我正在开发一个 Flutter 应用程序作为一个项目,但我不知道如何获得两次之间的差异。我得到的第一个是从 firebase 作为字符串,然后我使用 this:DateTime.parse(snapshot.documents[i].data['from']) 将其格式化为 DateTime,例如它给了我 14:00 。然后,第二个是DateTime.now()。 我尝试了所有方法differencesubtract,但没有任何效果!

请帮助我获得这 2 次之间的确切持续时间。 我需要这个作为倒数计时器。

这是我的代码的概述:

.......

class _ActualPositionState extends State<ActualPosition>
    with TickerProviderStateMixin {
  AnimationController controller;
  bool hide = true;
  var doc;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void initState() {
    super.initState();
    var d = Firestore.instance
        .collection('users')
        .document(widget.uid);
    d.get().then((d) {
      if (d.data['parking']) {
        setState(() {
          hide = false;
        });
        Firestore.instance
            .collection('historyParks')
            .where('idUser', isEqualTo: widget.uid)
            .getDocuments()
            .then((QuerySnapshot snapshot) {
          if (snapshot.documents.length == 1) {
            for (var i = 0; i < snapshot.documents.length; i++) {
              if (snapshot.documents[i].data['date'] ==
                  DateFormat('EEE d MMM').format(DateTime.now())) {
                setState(() {
                  doc = snapshot.documents[i].data;
                });
                Duration t = DateTime.parse(snapshot.documents[i].data['until'])
                    .difference(DateTime.parse(
                        DateFormat("H:m:s").format(DateTime.now())));

                print(t);
              }
            }
          }
        });
      }
    });
    controller = AnimationController(
      duration: Duration(hours: 1, seconds: 10),
      vsync: this,
    );
    controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
  }

  double screenHeight;
  @override
  Widget build(BuildContext context) {
    screenHeight = MediaQuery.of(context).size.height;
    return Scaffold(

.............

【问题讨论】:

  • 我认为这个问题在这里解释得很好:stackoverflow.com/questions/52713115/…
  • 是的,实际上我已经检查过这个答案,这是因为两个日期之间的差异,我尝试使用相同的解决方案,但它没有用
  • 你能贴出你试过的代码吗
  • Duration t = DateTime.parse(snapshot.documents[i].data['from']).difference(DateTime.now()); 结果只是第一个值,即 18:00
  • 让我们试试这个:给我 snapshot.documents[i].data['from'] 的值,给我 Datetime.now() 的值和给 t.inSeconds 的值。所以我可以重现这种情况。否则我什么都做不了

标签: flutter datetime dart datetime-format


【解决方案1】:

您可以使用以下方法找到时间之间的差异:

DateTime.now().difference(your_start_time_here);

类似这样的:

var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.

来自 DartPad 的示例:

void main() {
  
    final startTime = DateTime(2020, 02, 20, 10, 30);
    final currentTime = DateTime.now();
  
    final diff_dy = currentTime.difference(startTime).inDays;
    final diff_hr = currentTime.difference(startTime).inHours;
    final diff_mn = currentTime.difference(startTime).inMinutes;
    final diff_sc = currentTime.difference(startTime).inSeconds;
  
    print(diff_dy);
    print(diff_hr);
    print(diff_mn);
    print(diff_sc);
}

输出:3, 77, 4639, 278381,

希望这有帮助!

【讨论】:

  • YEAAAAH 非常感谢它真的很有帮助.. 我试图获取现在同一天的年、月和日,并提取我的变量的小时和分钟以形成 startTime 所以差异它和 DateTime.now() 之间的值给了我正确的值.. TY 非常感谢您的帮助
  • DateFormat fd = DateFormat("HH:mm"); DateTime tt = fd.parse(snapshot.documents[i].data['until']); var diff = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, tt.hour, tt.minute, tt.second) .difference(DateTime.now());
【解决方案2】:

您可以使用 DateTime 类找出两个日期之间的差异。

DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11'); 
DateTime dateTimeNow = DateTime.now();

final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');

final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');

【讨论】:

    【解决方案3】:

    使用此代码:

    var time1 = "14:00";
    var time2 = "09:00";
    
    Future<int> getDifference(String time1, String time2) async 
    {
        DateFormat dateFormat = DateFormat("yyyy-MM-dd");
        
        var _date = dateFormat.format(DateTime.now());
        
        DateTime a = DateTime.parse('$_date $time1:00');
        DateTime b = DateTime.parse('$_date $time2:00');
        
        print('a $a');
        print('b $a');
        
        print("${b.difference(a).inHours}");
        print("${b.difference(a).inMinutes}");
        print("${b.difference(a).inSeconds}");
        
        return b.difference(a).inHours;
    }
    

    【讨论】:

      【解决方案4】:

      你可以使用这个方法

      getTime(time) {
        if (DateTime.now().difference(time).inMinutes < 2) {
          return "a few seconds ago";
        } else if (DateTime.now().difference(time).inMinutes < 60) {
          return "${DateTime.now().difference(time).inHours} min";
        } else if (DateTime.now().difference(time).inMinutes < 1440) {
          return "${DateTime.now().difference(time).inHours} hours";
        } else if (DateTime.now().difference(time).inMinutes > 1440) {
          return "${DateTime.now().difference(time).inDays} days";
        }
      }
      

      你可以称它为 getTime(time) 其中时间是 DateTime 对象。

      【讨论】:

        【解决方案5】:

        要计算两次之间的差异,您需要两个 DateTime 对象。如果您有没有日期的时间,则需要选择一个日期。请注意,这很重要,因为如果您使用的是遵守夏令时的当地时区,两个时间之间的差异可能取决于日期

        如果您的目标是显示从现在到本地时区的下一个指定时间需要多长时间:

        import 'package:intl/intl.dart';
        
        /// Returns the [Duration] from the current time to the next occurrence of the
        /// specified time.
        ///
        /// Always returns a non-negative [Duration].
        Duration timeToNext(int hour, int minute, int second) {
          var now = DateTime.now();
          var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
        
          // If the time precedes the current time, treat it as a time for tomorrow.
          if (nextTime.isBefore(now)) {
            // Note that this is not the same as `nextTime.add(Duration(days: 1))` across
            // DST changes.
            nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
          }
          return nextTime.difference(now);
        }
        
        void main() {
          var timeString = '14:00';
        
          // Format for a 24-hour time.  See the [DateFormat] documentation for other
          // format specifiers.
          var timeFormat = DateFormat('HH:mm');
        
          // Parsing the time as a UTC time is important in case the specified time
          // isn't valid for the local timezone on [DateFormat]'s default date.
          var time = timeFormat.parse(timeString, true);
        
          print(timeToNext(time.hour, time.minute, time.second));
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-30
          • 2016-02-13
          • 2015-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多