Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DateTimeFormatter withZone not working

I'm formatting a UTC date and I want it displayed in local time. However, using withZone(ZoneId.systemDefault()); does nothing. Here's some code, and the values of d and d2 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);
like image 263
CodyMace Avatar asked Aug 25 '26 19:08

CodyMace


1 Answers

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) {
    e.printStackTrace();
}
like image 188
techfly Avatar answered Aug 28 '26 08:08

techfly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!