Dart:解析日期时区给出UnimplementedError [英] Dart : parse date timezone gives UnimplementedError
问题描述
我需要在我的 Flutter 应用程序(来自JSON)中以以下格式解析日期:
I need to parse a date in the following format in my Flutter application (come from JSON) :
2019-05-17T15:03:22.472 + 0000
根据文档,我必须使用 Z
来获取时区( RFC 822格式的最后5个字符),因此我使用以下代码:
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:
中的日期解析后剩余的字符2019-05-17T15:03:22.472 + 0000
FormatException: Characters remaining after date parsing in 2019-05-17T15:03:22.472+0000
这是另一项测试:
/// 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());
}
是否已实施 Z
?
推荐答案
来自 DateFormat
类文档:
DateFormat用于以对语言环境敏感的方式格式化和解析日期。
DateFormat is for formatting and parsing dates in a locale-sensitive manner.
您不是要解析语言环境-敏感的日期字符串,而是 ISO 8601 日期字符串,因此,您不应使用 DateFormat
类。
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.
相反,请使用 DateTime.parse
方法,根据其文档,该方法支持您描述的格式:
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:与 2002-02-27T19:00:00Z相同
这篇关于Dart:解析日期时区给出UnimplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!