Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a date with the timezone "Etc/GMT"

Tags:

java

date

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.

like image 433
pgsandstrom Avatar asked Nov 30 '11 09:11

pgsandstrom


1 Answers

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);
like image 198
Friso Avatar answered Sep 20 '22 00:09

Friso