Dart : parse date timezone gives UnimplementedError

六月ゝ 毕业季﹏ 提交于 2020-06-16 04:46:09

问题


I need to parse a date in the following format in my Flutter application (come from JSON) :

2019-05-17T15:03:22.472+0000

According to the documentation, I have to use Z to get the time zone (last 5 characters in RFC 822 format), so I use the following :

new DateFormat("y-M-d'T'H:m:s.SZ").parseStrict(json['startDate']);

But it fails with error :

FormatException: Characters remaining after date parsing in 2019-05-17T15:03:22.472+0000

Here is another test :

/// THIS WORKS
try {
    print(new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(DateTime.now()));
} catch (e) {
    print(e.toString());
}

/// THIS RETURNS `UnimplementedError` (as soon as I use a 'Z' or 'z') somewhere
try {
    print(new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(DateTime.now()));
} catch (e) {
    print(e.toString());
}

Is Z implemented ?


回答1:


From the DateFormat class docs:

DateFormat is for formatting and parsing dates in a locale-sensitive manner.

You're not asking to parse a locale-sensitive date string but rather an ISO 8601 date string, so thus you should not use the DateFormat class.

Instead, use the DateTime.parse method, which supports the format you described, per its docs:

Examples of accepted strings:

  • ...
  • "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"



回答2:


Sadly z and v patterns are not implemented.

Those won't be implemented until Dart DateTime's have time zone information

More info on this issue https://github.com/dart-lang/intl/issues/19



来源:https://stackoverflow.com/questions/56189407/dart-parse-date-timezone-gives-unimplementederror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!