UTC中的DateTime不转换为Local [英] DateTime in UTC not converting to Local

查看:32
本文介绍了UTC中的DateTime不转换为Local的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了来自API的 DateTime 响应,该响应将时区设置为UTC.

I'm receiving a DateTime response from API that's sets the timezone to UTC.

但是当我尝试使用 toLocal()转换接收到的数据时,它不会转换.

But when I try to convert the received data using toLocal() it doesn't convert.

我的当地时间是 HKT

这是我的代码.

    //TIME DIFFERENCE
  getNotificationDate(DateTime date) {
    date = date.toUtc();
    final convertedDate = date.toLocal();

    final dateNow = DateTime.now();
    print('TIMENOW: ' + dateNow.toString());
    print('TIMENOTIFC: ' + convertedDate.toString());
    final difference = dateNow.difference(convertedDate);
    print('DIFFERENCE: ' + difference.toString());
    return getDurationFormat(difference);
  }

date 是我从API收到的 DateTime .这是UTC时区.

date is the DateTime I'm receiving from the API. which is in UTC timezone.

我使用了 print('TIMEZONENAME:'+ date.timeZoneName; ,它会自动将时区设置为 HKT .这就是为什么当我尝试使用 date.toLocal()

I used print('TIMEZONENAME: ' + date.timeZoneName; and it automatically sets the timezone to HKT. that's why it does nothing when I try to use date.toLocal()

推荐答案

Flutter提供了最简单的转换方法.您只需在解析日期时传递 utc:true .

Flutter gave us the easiest way to convert it. You just need to pass utc: true while parsing your date.

var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(dateUtc, true);
var dateLocal = dateTime.toLocal();

输入:

假设我的时区:+05:30

Assume my TimeZone : +05:30

UTC日期-> 2020-02-12 23:57:02.000

UTC Date -> 2020-02-12 23:57:02.000

输出:

本地日期-> 2020-02-12 18:27:02.019660

Local Date -> 2020-02-12 18:27:02.019660

这篇关于UTC中的DateTime不转换为Local的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆