Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ZoneOffset, ZoneId with LocalDateTime properly in Java 8?

Tags:

java

java-time

The objective here is to convert LocalDateTime to epoch second back and forth.

Suppose I have a LocalDateTime defined as:

LocalDateTime now = LocalDateTime.now();

I want to convert it to epoch second in time Asia/Kolkata time zone which I can do like:

long epochSecondNow = now.atZone(ZoneId.of("Asia/Kolkata")).toEpochSecond();

Now, I want to generate the 'now' again from epochSecondNow:

LocalDateTime class has a method ' ofEpochSecond(long epochSecond,long nanoOfSecond, ZoneOffset zoneOffset)' which takes epoch second, nano of second and ZoneOffset as arguments.

I am not able to create ZoneOffset using "Asia/Kolkata". How should I make the ZoneOffset object for my zone in order to make use of 'ofEpochSecond' method. Is there any other way?

Thanks!

like image 470
Anmol Gupta Avatar asked Dec 08 '15 09:12

Anmol Gupta


People also ask

How do I set LocalDateTime with timezone?

In your case: // your local date/time with no timezone information LocalDateTime localNow = LocalDateTime. now(); // setting UTC as the timezone ZonedDateTime zonedUTC = localNow. atZone(ZoneId.

How do I parse LocalDateTime to ZonedDateTime?

Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime to ZonedDateTime , we can use . atZone(ZoneId. systemDefault()) to create a ZonedDateTime containing the system default time zone and convert it to another time zone using a predefined zone id or offset.

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.

What is a ZonedDateTime in the Java 8 date and time API?

ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times.


1 Answers

Try use with Instant.ofEpochSecond

Instant instant = Instant.ofEpochSecond(epochSecondNow);
ZonedDateTime atZone = instant.atZone(ZoneId.of("Asia/Kolkata"));
LocalDateTime localDateTime = atZone.toLocalDateTime();

If you want to use with system time zone, can do with ZoneId.systemDefault()

like image 156
Viet Avatar answered Oct 02 '22 15:10

Viet