Java 8 timezone conversion

Viewed 2987

I know there are similar questions like this, but I wasn't quite able to find the example similar to mine. I learned about LocalDateTime and ZonedDateTime but I don't know how to tell my ZonedDateTime what's assumed timezone of parsed date.

I'm migrating from Java 7 to Java 8. In my code, I have a method like this:

public String changeTZ(String tzFrom, String tzTo, String dateToChange) {
    ZoneId zoneFrom = ZoneId.of(tzFrom);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat.toPattern());
    LocalDateTime localtDateAndTime = LocalDateTime.parse(dateToChange, formatter);
    ZonedDateTime dateAndTimeINeed = ZonedDateTime.of(localtDateAndTime, zoneFrom );

    ZonedDateTime rezDate = dateAndTimeINeed.withZoneSameInstant(ZoneId.of(tzTo));

    return formatter.format(rezDate);
}

Example usage is:

String rez = changeTZ("CEST", "UTC", "2017-08-10 14:23:58");

As you can see it receives datetime in form of string, timezone date is in tzFrom variable and TZ I need (toTo variable).

Code which does that in Java 7 is absurd and complex so I won't enlist it here. Can you please tell me how to achieve the same in Java 8 without changing method interface (arguments and return type)? What about DST? Is it handled automatically in Java 8?

Note that method also supports timezones in form of "CEST", "CET", "UTC" as well as standard ones like "Europe/London".

3 Answers
Related