为什么此代码会生成错误:“无法解析日期”
我正在尝试使用 SimpleDateFormat 类从该字符串中解析 DateTime:
Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)
我尝试了以下格式字符串:
String example = "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)";
SimpleDateFormat formatter = new SimpleDateFormat("E M d y H:m:s z");
try
{
Date exampleDate = formatter.parse(example);
LOGGER.warn(exampleDate.toString());
}
catch(Exception e)
{
LOGGER.warn(e.getMessage(), e);
}
但它生成了错误:
Unparseable date: "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)"
所以我尝试删除示例字符串的括号结束部分:
String example = "Sun Jan 09 2011 22:00:00 GMT+0000";
但它生成了相同的错误。
WARNING: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"
java.text.ParseException: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"
关于如何解决这个问题有任何提示吗?
I'm trying to use the SimpleDateFormat class to parse a DateTime out of this string:
Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)
I tried the following format string:
String example = "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)";
SimpleDateFormat formatter = new SimpleDateFormat("E M d y H:m:s z");
try
{
Date exampleDate = formatter.parse(example);
LOGGER.warn(exampleDate.toString());
}
catch(Exception e)
{
LOGGER.warn(e.getMessage(), e);
}
But it generates the error:
Unparseable date: "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)"
So I tried removing the parenthesized end part of the example string:
String example = "Sun Jan 09 2011 22:00:00 GMT+0000";
But it generates the same error.
WARNING: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"
java.text.ParseException: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"
Any hints on how to get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据 http://download.oracle.com /javase/1.4.2/docs/api/java/text/SimpleDateFormat.html 格式需要为:
这包括常规时区和 RFC 822 时区。
或者您可以将输入日期更改为:
,这将仅容纳
z
。(注意最后一部分中的冒号。)
According to http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html the format needs to be:
This includes the general timezone and the RFC 822 time zone.
Or you could change your input date to:
which would accomodate just
z
.(Note the colon in the last part.)
您应该使用(或
Z
仅用于最后一部分):You should use (or
Z
only for last part):如果您想解析文本月份,您还需要使用“MMM”。来自 javadocs:
“月份:如果模式字母的数量为 3 个或更多,则月份被解释为文本;否则,它被解释为数字。”
You also need to use "MMM" if you want to parse textual months. From the javadocs:
"Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number."
我认为问题在于
z
修饰符无法解析GMT+0000
。根据 Javadoc 描述了z< /code> 解析
,格式类似于 GMT+HH:MM,而不是 GMT+HHMM。如果您想解析您所拥有的内容,您可能需要将格式字符串从 更改
为
I think that the problem is that the
z
modifier can't parseGMT+0000
. According to the Javadoc describing whatz
parses, the format is something like GMT+HH:MM, rather than GMT+HHMM. If you want to parse what you have, you probably want to change your format string fromto