在对 Dart SDK 的源代码进行了一些挖掘之后,看起来millisecondsSinceEpoch 属性或microsecondsSinceEpoch 属性用于计算两个DateTime 变量之间的差异。这可以解释为什么 UTC DateTime 值和本地 DateTime 值的差异是相同的,因为它们都代表相同的时间。
final now = DateTime.now();
final utc = now.toUtc();
final date = DateTime.parse('2020-07-01T19:00:00Z');
print(utc);
print(now);
print(date);
print(utc.microsecondsSinceEpoch);
print(now.microsecondsSinceEpoch);
print(date.microsecondsSinceEpoch);
print(utc.difference(date).inMinutes);
print(now.difference(date).inMinutes);
2020-07-01 16:26:54.464Z
2020-07-01 17:26:54.464
2020-07-01 19:00:00.000Z
1593620814464000
1593620814464000
1593630000000000
-153
-153
./sdk/lib/core/date_time.dart
/**
* The value of this DateTime.
*
* The content of this field is implementation dependent. On JavaScript it is
* equal to [millisecondsSinceEpoch]. On the VM it is equal to
* [microsecondsSinceEpoch].
*/
final int _value;
./js_runtime/lib/core_patch.dart
@patch
Duration difference(DateTime other) {
return new Duration(milliseconds: _value - other._value);
}
./vm/lib/date_patch.dart
@patch
Duration difference(DateTime other) {
return new Duration(microseconds: _value - other._value);
}
如果您不希望这种默认行为,那么您可以检查DateTime 值是否为isUtc。如果该值不是 UTC,那么您可以添加 timeZoneOffset 以实现您的预期行为。
extension DateTimeExtensions on DateTime {
Duration differenceTimeZoneOffset(DateTime other) {
if (this.isUtc) {
return this.difference(other);
} else {
return this.add(this.timeZoneOffset).difference(other);
}
}
}
final now = DateTime.now();
final utc = now.toUtc();
final date = utc.add(Duration(hours: 1));
print(utc);
print(now);
print(date);
print(utc.microsecondsSinceEpoch);
print(now.microsecondsSinceEpoch);
print(date.microsecondsSinceEpoch);
print(utc.differenceTimeZoneOffset(date).inMinutes);
print(now.differenceTimeZoneOffset(date).inMinutes);
2020-07-01 17:24:54.923Z
2020-07-01 18:24:54.923
2020-07-01 18:24:54.923Z
1593624294923000
1593624294923000
1593627894923000
-60
0