Java 8 Clock instant() method with Examples
Last Updated :
14 Apr, 2023
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.
Syntax:
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.
Example:
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()
Java
import java.time.*;
public class instantMethodDemo {
public static void main(String[] args)
{
Clock clock = Clock.systemDefaultZone();
Instant instantObj = clock.instant();
System.out.println("Instant for class " + clock
+ " is " + instantObj);
}
}
|
Output:
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.
Syntax:
// get ZonedDateTime object from instant object returned by instant() method of Clock class
ZonedDateTime time = Clock.systemDefaultZone().instant().atZone(Clock.getZone());
Code:
Java
import java.time.*;
public class instantMethodDemo {
public static void main(String[] args)
{
ZoneId zoneId = ZoneId.of("Europe/Paris");
Clock clock = Clock.system(zoneId);
Instant instantObj = clock.instant();
ZonedDateTime time = instantObj.atZone(clock.getZone());
System.out.println("Instant for class " + clock
+ " is " + time.toString());
}
}
|
Output:
Instant for class SystemClock[Europe/Paris] is 2018-08-21T07:31:13.525+02:00[Europe/Paris]
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#instant–
Share your thoughts in the comments
Please Login to comment...