Search code examples
javatimezonejava-timetimezone-offsetzoneddatetime

Can I get correct datetime from LocalDateTime in defferent zone?


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?


Solution

  • LocalDateTime is not tied to a locality or time zone

    Quoting extensive description of java.time, see answer with 1500+ upvotes, about LocalDateTime:

    They are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.

    Quoting more from extensive description of java.time, about java-time type usage:

    So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant and ZonedDateTime classes most commonly.

    Here is an example with one of the recommended types for specifying time zone "America/Los_Angeles":

    ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
    

    Here is another variation doing the same thing:

    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), ZoneId.of("America/Los_Angeles"));
    

    And another variation doing the same thing:

    ZonedDateTime zonedDateTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
    

    You can see Available Zone Ids by using ZoneId.getAvailableZoneIds():

    ZoneId.getAvailableZoneIds().stream().forEach(System.out::println);
    

    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