CodyMace CodyMace - 1 year ago 150
Android Question

Android DateTimeFormatter withZone not working

I'm formatting a UTC date and I want it displayed in local time. However, using

does nothing.
Here's some code, and the values of
are the same, but I'm expecting d2 to be 6 hours earlier because I'm in MST.

public static final String DATE_TIME_PATTERN = "uuuuMMddHHmmss";

String date = "20160908222020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN).withZone(ZoneId.systemDefault());
LocalDateTime d = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
LocalDateTime d2 = LocalDateTime.parse(date, formatter2);

Answer Source

Use SimpleDateFormat, it's easier to understand what's happening (and this approach worked for me).

public static final String SOURCE_DATE_FORMAT = "yyyyMMddHHmmss";
String date = "20160908222020";

SimpleDateFormat sourceDateFormat = new SimpleDateFormat(SOURCE_DATE_FORMAT);
sourceDateFormat.setTimeZone("UTC"); // set this to whatever the source time zone is

String adjustedDate = "";
try {
    Date parsedDate = sourceDateFormat.parse(date);
    adjustedDate = DateFormat.getDateTimeInstance().format(parsedDate); // getDateTimeInstance() returns the local date/time format (in terms of language/locale and time zone) of the device and format() formats the parsed date to fit that instance
} catch (ParseException e) {