首页 > 解决方案 > 寻找具有不同时区的 2 个 DateTime 对象的差异?

问题描述

我需要设置other对象的时区以匹配now具有 utc 时区的对象。

我正在比较两个日期时间对象,但“差异”值与预期值不匹配。最有可能归结为两个对象具有不同的时区(Utc 和 Bst)。

void main() {
   var now = new DateTime.now().toUtc();
  print(now);
  print(now.timeZoneName);
   var other = DateTime.parse("2020-05-22 18:27:32.608069");  
  print(other);
  print(other.timeZoneName);
   var diff = now.difference(other);
    print(diff);

}

output:
2020-05-22 19:26:39.169Z
UTC
2020-05-22 18:27:32.608
British Summer Time
1:59:06.561000

标签: dart

解决方案


您不想转换,您想以 UTC 格式读取日期/时间。

改变

var other = DateTime.parse("2020-05-22 18:27:32.608069"); 

var other = DateTime.parse("2020-05-22 18:27:32.608069z"); 

如果 other 已经构建,则需要使用DateTime.utc()

https://api.dart.dev/stable/2.8.2/dart-core/DateTime/DateTime.utc.html

var newDate = new DateTime.utc(other.year, other.month, other.day, other.hour, other.minute, other.second, other.millisecond, other.microsecond);

推荐阅读