2011-11-30 138 views
7

我第一次尝试的日期:解析与时区 “ETC/GMT”

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”

EDIT2:我宁愿不完全删除时区信息。我正在编写一个接收来自外部用户的日期的服务器,所以其他日期可能有其他时区。 更确切地说:我收到的这个特定日期来自苹果服务器在iphone应用程序中进行应用程序购买后的收据,但我也可以从其他来源获得日期。

+0

将小'z'离开。它不会考虑时区。你的代码将正常工作! – HashimR

回答

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(); 
      } 

+0

Damnit,由于某种原因,我刚刚得到“java.text.ParseException:Unparseable date:”2011-09-02 10:26:35 Etc/GMT“”。怎么会这样?我已经检查过getTimeZone()不返回null或类似的东西。 – pgsandstrom

+0

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);它会工作从for​​mater删除区域信息 – Rupok

0

它并没有为我工作,要么事情是我尝试设置SimpleDateFormatter到“ETC/GMT”的时区,然后格式化这里的新日期为输出:

2011-11-30 10时46分32秒GMT + 00:00

所以其他/ 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"); 

工作正常。

+0

我认为问题的重点不是忽略时区,而是要考虑到它。如果字符串包含例如“ “美国/洛杉矶”时区。 –

3

不知道,如果这个问题仍然是与你有关的,但是如果你使用乔达时间,这会工作:

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

没有乔达时间下面的工作(虽然有点更多的工作):

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);