Java日期解析时区导致解析错误 [英] Java Date Parsing Timezone causing parse error

查看:104
本文介绍了Java日期解析时区导致解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 字符串日期= 

我收到一个ParseException与以下代码,我似乎无法解决它: 2012年3月13日星期二10:48:05 GMT-0400
SimpleDateFormat format = new SimpleDateFormat(EEE MMM dd yyyy HH:mm:ss zzzX); //尝试最后的zzzZ以及
System.out.println(format.parse(date));

如果我在SimpleDateFormat的结尾处拿出-0400和X(或Z)工作正常,但一旦它在代码中,它根本不起作用。应该使用什么符号?我正在使用Java 7。



这是我收到的解析错误:

  java.text.ParseException:不可稀释的日期:Tue Mar 13 2012 10:48:05 GMT-0400
在java.text.DateFormat.parse(DateFormat.java:357)
java.text.ParseException:不可稀释日期:Tue Mar 13 2012 10:48:05 GMT-0400
在java.text.DateFormat.parse(DateFormat.java:357)
在com.throwaway .parse.DateParsing.testDate(TestDate:17)


解决方案

您的字符串的 GMT 部分 GMT-0400 导致问题。

Z (或 X 在java 7)参数只匹配 -4000 。你必须通过使用这样的单引号逃避 GMT

  DateFormat format = new SimpleDateFormat(EEE MMM dd yyyy HH:mm:ss'GMT'Z,Locale.US); 

请注意,放一个 Local 在您的DateFormat。没有它,您的代码将无法在其他国家/地区使用(如法国这样)。


I'm receiving a ParseException with the following code and I can't seem to fix it:

String date = "Tue Mar 13 2012 10:48:05 GMT-0400";
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzzX"); //Tried zzzZ at the end as well
System.out.println(format.parse(date));

If I take out the -0400 and the X (or Z) at the end of the SimpleDateFormat things work fine, but once it's in the code, it simply doesn't work. What symbol should I be using instead? I'm using Java 7.

Here is the parse error I receive:

java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.throwaway.parse.DateParsing.testDate(TestDate:17)

解决方案

The GMT part of GMT-0400 of your string is causing the problem.
The Z (or X in java 7) parameter is only matching -4000. You have to escape GMT by using single quotes like this :

DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.US);

Note that it's also a good practice to put a Local in your DateFormat. Without it your code won't work in other countries (like here in France...).

这篇关于Java日期解析时区导致解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆