Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get `Instant` from `ZonedDateTime` in java.time

Given a ZonedDateTime in the java.time package of Java 8 and later, how does one obtain an Instant?

Going the other way ( InstantZonedDateTime ) is simply:

ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ) ;

Going from ZonedDateTimeInstant is needed for things like converting to the old-school java.util.Date class.

java.util.Date date = Date.fromInstant( instant ) ;
like image 498
Basil Bourque Avatar asked Aug 11 '15 08:08

Basil Bourque


People also ask

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.

Does Instant NOW () return UTC time?

now() now() method of a Instant class used to obtain the current instant from the system UTC clock. This method will return instant based on system UTC clock.

Does Java instant have timezone?

It doesn't have a time zone. It doesn't represent a date but an instance in time in milliseconds since the Unix epoch (1970).

How do you convert instant to timezone?

Conversion Instant instant = Instant. now(); Now we will call the atZone() method on the instant object to convert it to a ZonedDateTime object. ZonedDateTime zonedDateTime = instant.


1 Answers

You can use the toInstant() default method from ChronoZonedDateTime interface (which is inherited by ZonedDateTime.

screenshot of documentation page for ChronoZonedDateTime class with method toInstant highlighted

like image 179
Codebender Avatar answered Oct 06 '22 11:10

Codebender