morristech
4/30/2018 - 9:05 PM

Parsing timestamps in Android without Jodatime.

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