Given a ZonedDateTime
in the java.time package of Java 8 and later, how does one obtain an Instant
?
Going the other way ( Instant
→ ZonedDateTime
) is simply:
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ) ;
Going from ZonedDateTime
→ Instant
is needed for things like converting to the old-school java.util.Date
class.
java.util.Date date = Date.fromInstant( instant ) ;
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.
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.
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).
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.
You can use the toInstant()
default method from ChronoZonedDateTime
interface (which is inherited by ZonedDateTime
.
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