java.text.Parse 异常:无法解析的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24192299/
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
java.text.Parse Exception : Unparseable Date
提问by user2133404
I have the following code:
我有以下代码:
String ModifiedDate = "1993-06-08T18:27:02.000Z" ;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date ModDate = sdf.parse(ModifiedDate);
I am getting the following exception even though my date format is fine...
即使我的日期格式很好,我也收到以下异常...
java.text.ParseException: Unparseable date: "1993-06-08T18:27:02.000Z"
at java.text.DateFormat.parse(DateFormat.java:337)
采纳答案by Sotirios Delimanolis
The Z
pattern latter indicates an RFC 822 time zone. Your string
在Z
后者模式表示RFC 822的时区。你的字符串
String ModifiedDate = "1993-06-08T18:27:02.000Z" ;
does not contain such a time zone. It contains a Z
literally.
不包含这样的时区。它包含一个Z
字面意思。
You'll want a date pattern, that similarly to the literal T
, has a literal Z
.
你会想要一个日期模式,类似于文字T
,有一个文字Z
。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
If you meant for Z
to indicate Zulu time, add that as a timezone when constructing the SimpleDateFormat
如果您打算Z
指示祖鲁时间,请在构建时区添加它SimpleDateFormat
sdf.setTimeZone(TimeZone.getTimeZone("Zulu"));;
回答by Basil Bourque
The answer by Sotirios Delimanolisis correct. The Z
means Zulu time, a zero offset from UTC (+00:00). In other words, not adjusted to any time zone.
Sotirios Delimanolis的回答是正确的。该Z
装置祖鲁时间,零从UTC(:00 00)的偏移量。换句话说,没有调整到任何时区。
Joda-Time
乔达时间
FYI, the Joda-Timelibrary make this work much easier, as does the new java.time packagein Java 8.
仅供参考,Joda-Time库使这项工作变得更加容易,Java 8中的新java.time 包也是如此。
The format you are using is defined by the ISO 8601standard. Joda-Time and java.time both parse & generate ISO 8601 strings by default.
您使用的格式由ISO 8601标准定义。Joda-Time 和 java.time 默认都解析和生成 ISO 8601 字符串。
A DateTime in Joda-Time knows its own assigned time zone. So as part of the process of parsing, specify a time zone to adjust.
Joda-Time 中的 DateTime 知道自己分配的时区。因此,作为解析过程的一部分,指定要调整的时区。
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( "1993-06-08T18:27:02.000Z", timeZone );
String output = dateTime.toString();
You can keep the DateTime object in Universal Timeif desired.
如果需要,您可以将 DateTime 对象保留在世界时。
DateTime dateTime = new DateTime( "1993-06-08T18:27:02.000Z", DateTimeZone.UTC );
When required by other classes, you can generate a java.util.Date object.
当其他类需要时,您可以生成一个 java.util.Date 对象。
java.util.Date date = dateTime.toDate();