Java parsing date with timezone from a string

爱⌒轻易说出口 提交于 2020-12-02 18:56:30

问题


I want to parse a date with timezone from a string in the format "31-12-2014 18:09 +05:30". I tried to parse using simple-Date-Format using "d-MM-yyyy HH:mm ZZ" and "d-MM-yyyy HH:mm Z". But it is giving me a un-parables date exception. How to do this? Please help me.


回答1:


SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm XXX");
Date d = sdf.parse("31-12-2014 18:09 +05:30");
System.out.println(d);

Note that you can't use X before SimpleDateFormat of JDK7, because it's the ISO 8601 time zone format.

With Java 6 you can only use ZZZ but it won't match +05:30 because Z match RFC 822 time zone format

If you're using Java 6, please refer to this answer : Converting ISO 8601-compliant String to java.util.Date




回答2:


use X instead of Z or ZZ as below:

String str = "31-12-2014 18:09 +05:30";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm X");
System.out.println(format.parse(str));
Output:
Wed Dec 31 18:39:00 IST 2014



回答3:


You have two errors: first, you should use two ds for the day. Second, use X instead of Z for the timezone. X represents the format that you are using. See the docs for more info. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

"dd-MM-yyyy HH:mm X"



回答4:


Others have pointed out the X option in Java SE 7. If you, however, have an older Java version, then you can change the timezone part to +0530, then it will work with Z (which is availabe even in Java SE 1.4).



来源:https://stackoverflow.com/questions/27721307/java-parsing-date-with-timezone-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!