飞镖日期时间.difference

Dart DateTime .difference

我想将计时器设置为每分钟一次 运行,但在编写程序时我发现了这种意外行为

void main() {
  final now = DateTime.now().toUtc();
  final minuteAfterNow = new DateTime(now.year,now.month,now.day,now.hour,now.minute +1,now.second,now.millisecond,now.microsecond);
  print(minuteAfterNow);
  print(now);
  print(minuteAfterNow.difference(now));
}

输出如下:

2020-12-30 09:41:06.508
2020-12-30 09:40:06.508Z
-1:59:00.000000

不应该差输出1分钟吗?这个输出是什么?

这是不同的,因为有 2 个问题:

1/ 您正在比较 UTC 和非 UTC,这将需要额外的偏移量 :)。我给你改代码让你自己看:

 final now = DateTime.now().toUtc();
 final now1 = DateTime.utc(now.year, now.month, now.day,now.hour, now.minute, now.second + 1, now.millisecond, now.microsecond);
 final difference = now.difference(now1);
 print(difference);

2/ 你错过了秒、毫秒、微秒参数。一旦忽略它,默认情况下它将为零。请查看 Dart

中的 DateTime class
  DateTime.utc(int year,
      [int month = 1,
      int day = 1,
      int hour = 0,
      int minute = 0,
      int second = 0,
      int millisecond = 0,
      int microsecond = 0])
      : this._internal(year, month, day, hour, minute, second, millisecond,
            microsecond, true);

顺便说一句,下次请添加您的代码。快乐的编码。 :)

是的,我希望差异函数只计算两个日期之间的差异,而不检查它们是否是 Utc,这是不正确的

 external DateTime._internal(int year, int month, int day, int hour,
      int minute, int second, int millisecond, int microsecond, bool isUtc);

这就是为什么下面的代码给出了所需的输出,即使日期与之前相同。

final now = DateTime.now();
  final now2 = now.toUtc();
  final minuteAfterNow = new DateTime(now.year,now.month,now.day,now.hour,now.minute +1,now.second,now.millisecond,now.microsecond).toUtc();
  print(minuteAfterNow);
  print(now2);
  print(minuteAfterNow.difference(now2).inMinutes);

输出:
2020-12-30 09:37:52.559Z
2020-12-30 09:36:52.559Z
1