Search code examples
java-8timezonejava-timetimezone-offsetlocaltime

Adjust LocalTime according to ZoneId


Given a LocalTime in a given ZoneId, how can I find the adjusted LocalTime on UTC?

I am looking for something similar to .atZone from LocalDateTime, but couldn't find anything.

I suspect I can use it with atOffset, but I don't really understand how to use it.

So for example:

LocalTime: 15:00
ZoneId: America/Sao_Paulo (GMT -3)
Output: 18:00

Solution

  • You need to give a date too. In case the zone has summer time (DST), for example, this is needed to apply the correct offset (I don’t know whether São Paulo uses summer time, but Java requires a date always).

    And still this takes one more step than what you might have expected, but it’s straightforward enough once you know how. For the case of demonstration I have assumed you meant 15:00 today, which you hardly did, but I trust you to fill in the desired date yourself.

        LocalTime time = LocalTime.of(15, 0);
        LocalTime utcTime = LocalDateTime.of(LocalDate.now(), time)
                .atZone(ZoneId.of("America/Sao_Paulo"))
                .withZoneSameInstant(ZoneOffset.UTC)
                .toLocalTime();
        System.out.println(utcTime);
    

    This prints the result you also asked for

    18:00