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!
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With