I saved current date time in database using LocalDateTime.now()
, i see that it is saved as Map
of key-value, In the map i see key for time, month , year, second , nano --etc. But i see nowhere information regarding zone. So if retrieve same time date in different zone say USA (data saved from India) then how to do it?
Can I get correct datetime from LocalDateTime in defferent zone?
290 views Asked by Rafa AtThere are 3 answers
As shown in the overview of modern date-time classes in Java, the classes which have time-zone information are ZonedDateTime
, OffsetDateTime
, OffsetTime
etc. The class, LocalDateTime
does not have time-zone information.
As mentioned here,
The class that handles both date and time, without a time zone, is LocalDateTime, one of the core classes of the Date-Time API. This class is used to represent date (month-day-year) together with time (hour-minute-second-nanosecond) and is, in effect, a combination of
LocalDate
withLocalTime
. This class can be used to represent a specific event, such as the first race for the Louis Vuitton Cup Finals in the America's Cup Challenger Series, which began at 1:10 p.m. on August 17, 2013. Note that this means 1:10 p.m. in local time. To include a time zone, you must use aZonedDateTime
or anOffsetDateTime
, as discussed in Time Zone and Offset Classes.
Given below is an example code for working with OffsetDateTime
:
OffsetDateTime odt = OffsetDateTime.now(ZoneOffset.UTC);// Change ZoneOffset as applicable
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();
Learn more about the modern date-time API at Trail: Date Time.
LocalDateTime is not tied to a locality or time zone
Quoting extensive description of java.time, see answer with 1500+ upvotes, about LocalDateTime:
Quoting more from extensive description of java.time, about java-time type usage:
Here is an example with one of the recommended types for specifying time zone "America/Los_Angeles":
Here is another variation doing the same thing:
And another variation doing the same thing:
You can see Available Zone Ids by using ZoneId.getAvailableZoneIds():
Learn more about java.time at:
extensive description of java.time, see answer with 1500+ upvotes.
You can read more about ZonId and ZoneOffset here: https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html https://docs.oracle.com/javase/10/docs/api/java/time/ZoneOffset.html