Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 269
Matheus208 Avatar asked Jun 07 '17 14:06

Matheus208


People also ask

What is ZoneId of UTC?

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.

What is ZoneId systemDefault ()?

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.

What is the difference between a ZoneId and a ZoneOffset?

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.

How do I change timezone in LocalDateTime?

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 .


2 Answers

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
like image 92
Ole V.V. Avatar answered Sep 27 '22 01:09

Ole V.V.


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
like image 22
Meno Hochschild Avatar answered Sep 23 '22 01:09

Meno Hochschild