Parse a date with the timezone "Etc/GMT"

My first attempt was:

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

It throws ParseException, so I found this hack:

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

It did not work either, and now I'm stuck. It parses without problems if I just change the timezone to "GMT".

edit: An example string to parse would be "2011-11-29 10:40:24 Etc/GMT"

edit2: I would prefer not to remove timezone information completely. I am coding a server that receives the date from an external user, so perhaps other dates will have other timezones. To be more precise: This specific date I receive is from the receipt from the apple server after making an in app purchase on an iphone app, but I could also receive dates from other sources.


Don't know if this question is still relevant to you, but if you use Joda time, this'll work:

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

Without Joda time the following will work (bit more work though):

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

It didn't work for me either the thing is I tried setting TimeZone of SimpleDateFormatter to "Etc/GMT" and then formatted a new date here is the output:

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

So Etc/GMT is being translated as GMT+00:00

If you really want to stick to parse "2011-09-02 10:26:35 Etc/GMT" then following will help too without even considering explicit Timezone change:

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

Works fine.


以下代码正在为我工​​作


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

链接地址: http://www.djcxy.com/p/10168.html

上一篇: 结合RSpec过滤器?

下一篇: 用时区“Etc / GMT”解析日期