在颤动中将字符串转换为DateTime

我有这个代码

if (obj.due_date != null) {
      print('The date is  '+obj.due_date);
      print('now change to ' +
       DateUtil().formattedDate(DateTime.parse(obj.due_date)));
 }

DateUtil

import 'package:intl/intl.dart';

class DateUtil {
  static const DATE_FORMAT = 'dd/MM/yyyy';
  String formattedDate(DateTime dateTime) {
    print('dateTime ($dateTime)');
    return DateFormat(DATE_FORMAT).format(dateTime);
  }
}

我的输出变成这个

  

I / flutter(5209):日期是2019-11-20T00:00:00.000 + 08:00

     

I / flutter(5209):dateTime(2019-11-19 16:00:00.000Z)

     

I / flutter(5209):现在更改为19/11/2019

为什么它将从20变为19?

gukoule 回答:在颤动中将字符串转换为DateTime

这是因为您拥有

obj.due_date

根据日志,当前值为

  

2019-11-20T00:00:00.000 + 08:00

使用以下代码时

var tempDate = '2019-11-20T00:00:00.000+00:00';
print('The date is  '+tempDate);
print('now change to ' +DateUtil().formattedDate(DateTime.parse(tempDate)));

日志如下:

I/flutter (18268): The date is  2019-11-20T00:00:00.000+00:00
I/flutter (18268): dateTime (2019-11-20 00:00:00.000Z)
I/flutter (18268): now change to 20/11/2019

这些代码之间的唯一变化是我们传递的值。

  

2019-11-20T00:00:00.000 + 00:00

这纯粹是时区问题。

尝试下面的代码

var tempDate = DateTime.now().toLocal().toString();

日志显示

I/flutter (18268): 2019-11-15 16:06:54.786814
I/flutter (18268): The date is  2019-11-15 16:06:54.787186
I/flutter (18268): dateTime (2019-11-15 16:06:54.787186)
I/flutter (18268): now change to 15/11/2019

同样,当您使用以下代码时

var tempDate = DateTime.now().toUtc().toString();

日志如下:

I/flutter (18268): 2019-11-15 16:07:35.078897 
I/flutter (18268): The date is  2019-11-15 05:07:35.079251Z 
I/flutter (18268): dateTime (2019-11-15 05:07:35.079251Z) 
I/flutter (18268): now change to 15/11/2019

因此,最后的答案是,在行

下进行更改
DateUtil().formattedDate(DateTime.parse(tempDate)));

DateUtil().formattedDate(DateTime.parse(tempDate).toLocal())
本文链接:https://www.f2er.com/3097907.html

大家都在问