dart - 寻找具有不同时区的 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
解决方案
您不想转换,您想以 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);
推荐阅读
- django - 如何重构我的 Django 代码?
- javascript - PHP 表单和 Ajax 的问题
- c++ - 调用 glDrawElements 会破坏某些 GPU 上的显示?
- python - 将嵌套 Python dict 与 list 和 dict 进行比较
- c# - Unity Holotoolkit Spriterender
- excel - 使用 vba 更新 Excel 中的标题,不会覆盖现有值
- facebook - Intragram 图形 API Webhook
- python - 无法导入我刚刚安装的包
- python - 类变量 NameError 未定义 python
- python - Python:具有起点 p 的列表(递归函数)的总和