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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With