Cannot convert Sydney to Brisbane LocalDateTime in Java8

Viewed 317

Trying to convert String date which is in Australia/Sydney to Australia/Brisbane. I want this in Java8 using LocalDateTime

I have tried with date and works fine but date is deprecated.

    String sdate = "2019-01-14T01:42:00.19+11:00";

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    format.setTimeZone(TimeZone.getTimeZone("Australia/Brisbane"));
    try {
        Date  dd = format.parse(sdate);
        DateFormat teradataFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(teradataFormate.format(dd));
    } catch (ParseException e) {
        e.printStackTrace();
    }


    //Code that doesn't work with LocalDateTime 
     String sdate = "2019-01-14T01:42:00.19+11:00";

    LocalDateTime ldt = LocalDateTime.parse(sdate, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"));
    ZonedDateTime brisy = ldt.atZone(ZoneId.of("Australia/Brisbane"));
    DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(format1.format(brisy));  

expected : 2019-01-14 00:42:00 actual :2019-01-14 01:42:00

1 Answers
  1. Use ZonedDateTime instead of LocalDateTime. LocalDateTime doesn't support daylight savings.

  2. Use withZoneSameInstant() intead of withZoneSameLocal

    ZonedDateTime sydneyTime = ZonedDateTime.parse(sdate);
    ZonedDateTime brisyTime = sydneyTime.withZoneSameInstant(ZoneId.of("Australia/Brisbane"));
    DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(brisyTime.format(format1));
    
Related