java.text.ParseException:无法解析的日期“yyyy-MM-dd'T'HH:mm:ss.SSSZ” - SimpleDateFormat

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20168647/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:40:50  来源:igfitidea点击:

java.text.ParseException: Unparseable date "yyyy-MM-dd'T'HH:mm:ss.SSSZ" - SimpleDateFormat

javaparsingexceptiondatetimesimpledateformat

提问by Jacob

I would appreciate any help with finding bug for this exception:

我将不胜感激任何帮助查找此异常的错误:

java.text.ParseException: Unparseable date: "2007-09-25T15:40:51.0000000Z"

and following code:

和以下代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = sdf.parse(timeValue);
long mills = date.getTime();
this.point.time = String.valueOf(mills);

It throws expcetion with Date date = sdf.parse(timeValue);.

它抛出 expcetion Date date = sdf.parse(timeValue);

timeValue = "2007-09-25T15:40:51.0000000Z";, as in exception.

timeValue = "2007-09-25T15:40:51.0000000Z";,作为例外。

Thanks.

谢谢。

采纳答案by Reimeus

Zrepresents the timezone character. It needs to be quoted:

Z表示时区字符。需要引用:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

回答by DNA

In Java 7you can also use the Xpattern to match an ISO8601 timezone, which includes the special Z(UTC) value:

Java 7 中,您还可以使用该X模式来匹配 ISO8601 时区,其中包括特殊Z(UTC) 值:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX");
Date date = sdf.parse("2007-09-25T15:40:51.0000000Z");

However, it seems to require an exact number of millisecond characters in the pattern, which is not required for the 'Z' character pattern, and is rather inconvenient. I think this is because the ISO8601 definition also includes "two-digit hours", which are just numbers, so cannot be distinguished by the parser from the preceding milliseconds.

但是,它似乎需要模式中精确数量的毫秒字符,这对于 'Z' 字符模式不是必需的,而且相当不方便。我认为这是因为 ISO8601 定义还包括“两位数小时”,它们只是数字,因此解析器无法将其与前面的毫秒区分开来。

So this version would be fine for timestamps down to second precision, less so for milliseconds.

因此,此版本适用于低至秒精度的时间戳,而不适用于毫秒。