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
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime . There are two distinct types of ID: Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times.
The systemDefault() method of the ZoneId class in Java is used to return the system default time-zone. Syntax: public String systemDefault() Parameters: This method does not accepts any parameters. Return Value: This method returns the zone ID.
ZoneId describes a time-zone identifier and provides rules for converting between an Instant and a LocalDateTime . ZoneOffset describes a time-zone offset, which is the amount of time (typically in hours) by which a time zone differs from UTC/Greenwich.
To convert a LocalDateTime to another time zone, you first apply the original time zone using atZone() , which returns a ZonedDateTime , then convert to the new time zone using withZoneSameInstant() , and finally convert the result back to a LocalDateTime .
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
A ZoneId
does not make sense because the date is missing but you can use a ZoneOffset
this way:
LocalTime time = LocalTime.of(15, 0);
ZoneOffset offset = ZoneOffset.ofHours(-3);
LocalTime utc =
OffsetTime.of(time, offset).withOffsetSameInstant(ZoneOffset.UTC).toLocalTime();
System.out.println(utc); // 18:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With