解析带有时区"Etc/GMT"的日期

8

我的第一次尝试是:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);

它会抛出ParseException异常,因此我发现了这个技巧:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);

它还是不起作用,现在我陷入了困境。如果我将时区更改为"GMT",它可以无问题地解析。
编辑:要解析的示例字符串将是“2011-11-29 10:40:24 Etc/GMT”。
编辑2:我不想完全删除时区信息。我正在编写一个接收来自外部用户的日期的服务器,因此可能会有其他时区的其他日期。 更准确地说:我收到的这个特定日期来自在iPhone应用程序上进行应用内购买后从苹果服务器接收到的收据,但我也可以从其他来源接收日期。

请将小写字母 z 去掉,这样它就不会考虑时区了。你的代码将能够正常工作! - HashimR
3个回答

3

不知道这个问题是否仍然与您相关,但如果您使用Joda时间库,那么这个方法可以解决问题:

DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)

没有Joda time,以下内容也可以实现(不过需要更多的工作):
String s = "2011-11-29 10:40:24 Etc/GMT";

// split the input in a date and a timezone part            
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);

// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);

// parse the timezoneless part
Date date = formatter.parse(dateString);

0

以下代码对我有效

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
            try { System.out.println( sdf.parse("2011-09-02 10:26:35 Etc/GMT") ); 
            } catch (ParseException e){ 
                e.printStackTrace(); 
            }


该死,由于某种原因我只得到了“java.text.ParseException:无法解析的日期:” 2011-09-02 10:26:35 Etc/GMT“”。这怎么可能?我已经检查过getTimeZone()不会返回null或类似的东西。 - pgsandstrom
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 如果删除格式化程序中的区域信息,它将起作用。 - Rupok

0

这对我也没有用,问题是我尝试将SimpleDateFormatter的TimeZone设置为"Etc/GMT",然后格式化一个新日期,输出如下:

2011-11-30 10:46:32 GMT+00:00

所以Etc/GMT被转换为GMT+00:00

如果您真的想坚持解析"2011-09-02 10:26:35 Etc/GMT",那么以下内容也会有所帮助,甚至不需要考虑显式时区更改:

java.text.SimpleDateFormat isoFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Etc/GMT'");
isoFormat.parse("2010-05-23 09:01:02 Etc/GMT");

运行良好。


我认为问题的重点不是忽略时区,而是要考虑到它。如果字符串包含例如“America/Los_Angeles”时区,您的代码将给出错误的结果。 - Andrey Regentov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接