How to do Localdatetime(Datetimezone.forID("America/Sao_paulo")) in Java.time

Asked

Viewed 8,513 times

7

I wonder if there’s any way to mimic that code on java.time:

LocalDateTime(DateTimeZone.forID("America/Sao_Paulo"))

I don’t work very well with date in Java, if you can also explain to me what this code does.

1 answer

8


By code (DateTimeZone.forId), I’m assuming you’re using the Joda-Time.

In the case, DateTimeZone.forID("America/Sao_Paulo") creates an object that contains all Timezone information America/Sao_Paulo. Basically, the Timezone serves - among other things - to know the current date and time (taking into account things like daylight saving time and time zone changes throughout history - you can see more information on it wiki of the tag Timezone).

Now, at this very moment, in every part of the world, the date and current time may be different. In Brazil it is now March 15, 2019 at 4 pm, but in Japan it is already 16 at 4 am. In this case, the Timezone serves to know exactly what date and time values to use. The names in the format Continente/Regiao (as America/Sao_Paulo) are standardized by IANA (that maintains the timezone base that Java uses ¹).

When the builder of LocalDateTime gets a DateTimeZone, It uses the corresponding Timezone to know the values of the day, month, year, time, minute, second and milliseconds of the current date and time. In the case, the LocalDateTime will have the current date and time, according to Timezone America/Sao_Paulo (that is, the date and time values will be based on the Official Time of Brasilia).


In the java.time, the equivalent form is:

LocalDateTime.now(ZoneId.of("America/Sao_Paulo"))

The idea is the same. The class java.time.ZoneId creates an object corresponding to Timezone America/Sao_Paulo, and the method now() uses this Timezone to know the current date and time values.

Like LocalDateTime has no information about Timezone, the ZoneId is discarded (it is not part of the LocalDateTime, it was only used to get the values of the current date and time).


Remember that Joda-Time is not 100% identical to java.time (see this question for more details). Many classes have the same names and methods, and many of their concepts and ideas have been taken advantage of in Java 8. But there are several differences as well, and they are explained in more detail here and here.


(1): Joda-Time keeps its own copy of database IANA, separate from the JVM. Inclusive, this can be updated independently from the JVM.

  • 2

    It worked, great explanation, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.