我怎样才能得到2次之间的差异?

发布于 2025-01-11 11:55:08 字数 2251 浏览 0 评论 0原文

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

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

这是我的代码的概述:

.......

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(

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

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!

Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.

This is an overview of my code:

.......

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(

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

幸福%小乖 2025-01-18 11:55:08

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

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,

希望这有帮助!

you can find the difference between to times by using:

DateTime.now().difference(your_start_time_here);

something like this:

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.

example from 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);
}

Output: 3,
77,
4639,
278381,

Hope this helped!!

多孤肩上扛 2025-01-18 11:55:08

您可以使用 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');

You can use the DateTime class to find out the difference between two dates.

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');
不甘平庸 2025-01-18 11:55:08

使用此代码:

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;
}

Use this code:

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;
}
少女七分熟 2025-01-18 11:55:08

您可以使用此方法

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

,并且可以将其称为 getTime(time) 其中 time 是 DateTime 对象。

You can use this approch

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

And You can call it getTime(time) Where time is DateTime Object.

幼儿园老大 2025-01-18 11:55:08

要计算两个时间之间的差异,您需要两个 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));
}

To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.

If your goal is to show how long it will be from now to the next specified time in the local timezone:

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));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文