如何在 Dart 中将 UTC 日期时间字符串转换为本地日期时间?

发布于 2025-01-14 08:10:14 字数 258 浏览 2 评论 0原文

我从 API 2022-03-15T02:33:53.488427 获得了这个值,它是一个表示 UTC 时间戳的字符串,我当前的区域时间是 UTC-5,我正在尝试以下代码:

createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427').toLocal();

但是 createdAt 包含与原始字符串相同的日期时间,我缺少什么?

I got this value from an API 2022-03-15T02:33:53.488427, it is a string which represents a UTC timestamp, my current zone time is UTC-5, I'm trying this code:

createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427').toLocal();

But createdAt contains the same datetime like the original string, What I'm missing?

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

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

发布评论

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

评论(1

月下客 2025-01-21 08:10:14

字符串 2022-03-15T02:33:53.488427 不包含时区。因此,要告诉 Dart 您希望这是 UTC 时间,请在字符串后附加一个“Z”。然后它知道现在是祖鲁时间。否则,当它解析它时,它会假设您处于当地时间。
尝试

createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427Z').toLocal();

使用 print(createdDate?.timeZoneName) 确认 UTC 或您当地的时间

the string 2022-03-15T02:33:53.488427 does not include a timezone. So to tell Dart that you want this to be UTC time, then append a "Z" to the string. Then it knows that it is Zulu time. Otherwise it's going to assume that you are in local time when it parses it.
try

createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427Z').toLocal();

Use print(createdDate?.timeZoneName) to confirm UTC or your local

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