java Java从字符串中解析带有时区的日期

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

Java parsing date with timezone from a string

javadatedatetime

提问by Sumodh S

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.

我想从格式的字符串中解析带时区的日期"31-12-2014 18:09 +05:30"。我尝试使用"d-MM-yyyy HH:mm ZZ"和使用简单日期格式进行解析"d-MM-yyyy HH:mm Z"。但它给了我一个不可比喻的日期例外。这个怎么做?请帮我。

回答by alain.janinm

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 Xbefore SimpleDateFormat of JDK7, because it's the ISO 8601 time zone format.

请注意,不能XJDK7 的 SimpleDateFormat之前使用,因为它是 ISO 8601 时区格式。

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

使用 Java 6,您只能使用ZZZ但它不会匹配 +05:30,因为Z匹配 RFC 822 时区格式

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

如果您使用的是 Java 6,请参考这个答案:Converting ISO 8601-compatible String to java.util.Date

回答by SMA

use X instead of Z or ZZ as below:

使用 X 代替 Z 或 ZZ 如下:

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

回答by forgivenson

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

您有两个错误:首先,您应该d在当天使用两个s。其次,使用X代替Z时区。X代表您正在使用的格式。有关更多信息,请参阅文档。http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

"dd-MM-yyyy HH:mm X"

回答by meskobalazs

Others have pointed out the Xoption 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).

其他人已经指出了XJava SE 7 中的选项。但是,如果您有一个较旧的 Java 版本,那么您可以将时区部分更改为+0530,那么它就可以使用Z(即使在 Java SE 1.4 中也可以使用)。