Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ZonedDateTime to milliSecond in Java?

Tags:

I'm trying to convert ZonedDateTime to milliseconds using below code.

LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime zonedDateTime =ldt.atZone(ZoneId.of(""Asia/Kolkata"")); zonedDateTime.toInstant().toEpochMilli(); 

But this one returns milliseconds based on local time. And it's not considering ZoneId.

Let's say LocalDateTime("2019-04-10T05:30"). If I convert this to ZonedDateTime with Zone id ("Asia/Kolkata") then I'm getting ("2019-04-10T05:30+05:30[Asia/Kolkata]"). Then I convert to EpochMilli (1554854400000) = ("Wed Apr 10 2019 00:00:00") in UTC.

like image 402
Arun Avatar asked Apr 12 '19 06:04

Arun


People also ask

What is ZonedDateTime in Java?

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.

How do I get time from ZonedDateTime?

now() now() method of a ZonedDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return ZonedDateTime based on system clock with default time-zone to obtain the current date-time. The zone and offset will be set based on the time-zone in the clock.

Is ZonedDateTime a UTC?

A ZonedDateTime represents a date-time with a time offset and/or a time zone in the ISO-8601 calendar system. On its own, ZonedDateTime only supports specifying time offsets such as UTC or UTC+02:00 , plus the SYSTEM time zone ID.


1 Answers

You are using an Instant to get that milliseconds representation. Instant are not zone based. Now, the epoch time is based on the "1970-01-01T00:00:00Z" so you should not have the zone in it.

If you want to create a ZoneDateTime from the epoch value, you can simply create an Instant at that epoch time and then create a ZonedDateTime with the zone you wish :

//Let's create our zone time (just to keep your logic LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime zonedDateTime =ldt.atZone(ZoneId.of("Asia/Kolkata"));  //Then get the epoch on GMT long e = zonedDateTime.toInstant().toEpochMilli();  Instant i = Instant.ofEpochMilli(e); System.out.println(ZonedDateTime.ofInstant(i, ZoneId.systemDefault())); System.out.println(ZonedDateTime.ofInstant(i, ZoneId.of("Asia/Kolkata"))); 

2019-04-12T05:10:31.016+02:00[Europe/Paris]
2019-04-12T08:40:31.016+05:30[Asia/Kolkata]

NOTE : The code above should not be used like this, it is not necessary to get a LocalDateTime then a ZonedDateTime to finally create an Instant. This is just to show that even with a zone, this will be "lost" at one point.
Simply use :

long e = Instant.now().toEpochMilli(); 
like image 136
AxelH Avatar answered Oct 02 '22 12:10

AxelH