Java 8 Clock instant() method with Examples
Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8.
instant() method of Clock class returns a current instant of Clock object as Instant Class Object. Instant generates a timestamp to represent machine time. So this method generates a timestamp for clock object. Here returned Instant is Object of java.time.Instant class which represents a specific moment on the timeline in UTC Zone. This timeline is a count of nanoseconds since the epoch of the first moment of 1970 UTC. Since nowadays most of the business logic, data storage, and data exchange should be in UTC, so using Instant is useful.
public abstract Instant instant()
Return Value: This method returns the current instant of clock object.
Exception: This method throws a DateTimeException if the instant of clock object cannot be obtained.
Input:: a clock class Object e.g Clock.systemDefaultZone() Output:: instant e.g. 2018-08-19T20:22:23.366Z Explanation:: when instant() is called, it returns a current instant of Clock Class Object.
Below programs illustrates instant() method of java.time.Clock class:
Program 1: Get Clock object with systemDefaultZone using instant()
Instant for class SystemClock[Etc/UTC] is 2018-08-21T05:31:10.662Z
Program 2: Get Clock object with Zone “Europe/Paris” using instant()
To get zonal based date and time, get ZonedDateTime object from instant by using atZone(ZoneId zone) to print date and time of that Zone.
// get ZonedDateTime object from instant object returned by instant() method of Clock class ZonedDateTime time = Clock.systemDefaultZone().instant().atZone(Clock.getZone());
Instant for class SystemClock[Europe/Paris] is 2018-08-21T07:31:13.525+02:00[Europe/Paris]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.