Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created October 20, 2015 19:01
Show Gist options
  • Save patrickhammond/24b64717d1e1b18dbe62 to your computer and use it in GitHub Desktop.
Save patrickhammond/24b64717d1e1b18dbe62 to your computer and use it in GitHub Desktop.
Parsing timestamps in Android without Jodatime.
public static Date parseRawDateWithUnhandledException(String dateString) throws ParseException {
// This was previously being handled with Joda (yay!), but Joda eats up nearly 5000
// methods (boo!) in an already big app just to parse a timestamp...so there *is* a reason
// we are doing things like this...
if (dateString.endsWith("Z")) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("Zulu"));
return dateFormat.parse(dateString);
} else {
// Android formatting flags differ from the latest JDK formatting flags. Awesome.
try {
// Android compatible format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZ", Locale.US);
return dateFormat.parse(dateString);
} catch (Exception ex) {
// JDK compatible format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US);
return dateFormat.parse(dateString);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment