如何解决 java.text.ParseException: Unparseable date?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43737174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to solve java.text.ParseException: Unparseable date?
提问by Woppi
I'm trying to convert this to a readable format however, keep getting java.text.ParseException: Unparseable date: "2016-11-18T11:13:43.838Z" (at offset 23)
我正在尝试将其转换为可读格式,但是,请继续获取 java.text.ParseException: Unparseable date: "2016-11-18T11:13:43.838Z" (at offset 23)
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date date1 = df.parse("2016-11-18T11:13:43.838Z");
DateFormat outputFormatter1 = new SimpleDateFormat("dd-MMM-yyyy");
String output1 = outputFormatter1.format(date1); //
} catch (ParseException e) {
e.printStackTrace();
}
I read about adding locale as other SO answers suggested but it is still not working.
我阅读了有关按照其他 SO 答案的建议添加语言环境的内容,但它仍然无法正常工作。
回答by Manos Nikolaidis
According to the docsthe Z
in your format string indicates an RFC 822 time zone e.g. +01:00. You need to parse a ISO 8601 Time zone (the Z
in your input string indicating UTC timezone). You configure that with X
:
根据该文档的Z
在格式字符串表示RFC 822时区,例如+01:00。您需要解析 ISO 8601 时区(Z
在您的输入字符串中指示 UTC 时区)。您可以使用X
以下命令进行配置:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
回答by ΦXoc? ? Пepeúpa ツ
you are parsing a string that is not a correct representation of that pattern, you are missing the TimeZone... something like: -0600
您正在解析一个不是该模式的正确表示的字符串,您缺少时区...类似于: -0600
example:
例子:
Date date1 = df.parse("2016-11-18T11:13:43.838-0600Z");
here is the docfor more info....
这是有关更多信息的文档....
your code should look like:
您的代码应如下所示:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
Date date1 = df.parse("2016-11-18T11:13:43.838-0600Z");
DateFormat outputFormatter1 = new SimpleDateFormat("dd-MMM-yyyy");
String output1 = outputFormatter1.format(date1); //
} catch (ParseException e) {
e.printStackTrace();
}
回答by Malte Hartwig
Reading the Javadoc for SimpleDateFormat, I found that using Z
for timezone is very strict. It will not recognize "Z"
as zulu, it only accepts numeric timezone offsets.
You might want to try X
instead, which accept "Z"
according to the documentation.
阅读SimpleDateFormat的 Javadoc ,我发现使用Z
for timezone 非常严格。它不会识别"Z"
为祖鲁语,它只接受数字时区偏移量。您可能想尝试X
改为"Z"
根据文档接受。
回答by Felix Cruz
Please try this format
请试试这个格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");