Parse date with time zone "Etc / GMT"

My first attempt:

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

It throws a 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); 

That didn't work either, and now I'm stuck. It analyzes without problems if I just change the time zone to "GMT".

edit: An example line for parsing would be "2011-11-29 10:40:24 Etc / GMT"

edit2: I would prefer not to delete the time zone information completely. I am encoding a server that receives a date from an external user, so maybe other dates will have different time zones. More precisely: this particular date that I receive is obtained from the receipt from the Apple server after purchasing the application in the iphone application, but I could also receive dates from other sources.

+7
source share
3 answers

I don't know if this question applies to you, but if you use Joda time, this will work:

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

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

 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); 
+3
source

The following code works for me

    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
source

This did not work for me, or I tried to set TimeZone from SimpleDateFormatter to "Etc / GMT" and then formatted the new date, here is the result:

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

So Etc / GMT translates as GMT + 00: 00

If you really want to stick to the parsing "2011 / 12-02 10:26:35 Etc / GMT" , then the following hints will also help, without even considering the explicit change in Timezone:

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

It works great.

0
source

All Articles