UTC 中的日期时间未转换为本地

Gen*_*tle 18 datetime dart flutter

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

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

我的当地时间是香港时间

这是我的代码。

    //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);
  }
Run Code Online (Sandbox Code Playgroud)

编辑:

dateDateTime我从 API 收到的。这是在UTC时区。

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

Aan*_*hta 30

Flutter 为我们提供了最简单的转换方法。您只需要在解析日期时传递utc: true 即可

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

输入

假设我的时区:+05:30

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

输出

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

  • @Varundroid 就像, var dateTime = DateFormat("yyyy-MM-ddTHH:mm:ssZ").parse("2020-08-15T05:01:31Z", true); (2认同)

小智 13

我实施的两个解决方案

var date = DateFormat("yyyy-MM-ddTHH:mm:ss").parse(json, true);
var dateLocal  = date.toLocal();
Run Code Online (Sandbox Code Playgroud)

其他解决方案添加“Z”您需要向 DateTime.parse 指示时区,否则它假定本地时间。来自 dartdoc:

var date = DateTime.parse("${dateString}Z").toLocal();
var dateFormat = date2.toLocal();
Run Code Online (Sandbox Code Playgroud)


Ahm*_*san 10

首先,将您的文件转换StingDateTime.

> DateTime dateTime = DateTime.parse(json['pickUpTime']);
Run Code Online (Sandbox Code Playgroud)

其次,添加timeZoneOffSet到您转换后的日期时间,它将把 utc 转换为您的当地时间。

> dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
Run Code Online (Sandbox Code Playgroud)

最终代码

DateTime dateTime = DateTime.parse(json['pickUpTime']);
dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
Run Code Online (Sandbox Code Playgroud)


Cop*_*oad 8

// you have time in utc
var dateUtc = DateTime.now().toUtc();
print("dateUtc: $dateUtc"); // 2019-10-10 12:05:01

// convert it to local
var dateLocal = dateUtc.toLocal();
print("local: $dateLocal"); // 2019-10-10 14:05:01
Run Code Online (Sandbox Code Playgroud)

你能看到小时的差异吗,在UTC12和本地是14


Shy*_*dda 6

使用指定的格式(包括日期)将 UTC 时间转换为本地时间

var dateFormat = DateFormat("dd-MM-yyyy hh:mm aa"); // you can change the format here
var utcDate = dateFormat.format(DateTime.parse(uTCTime)); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate)); // you will local time
Run Code Online (Sandbox Code Playgroud)

正如我在这里回答的那样:https : //stackoverflow.com/a/65690095/2462531