Java 8 Clock Instant Method



In this article, we will learn how to use the instant() method in the Clock class in Java to obtain the current instant of a clock object. This method requires no parameters and returns an Instance representing the current timestamp of the clock. The Instant class is a part of the java.time package and represents a specific point on the timeline in UTC.

Problem Statement

Given the Clock class in the java.time package, use the instant() method to obtain the current instant of a clock object. The instant() method requires no parameters and returns an Instant representing the current time in the system's default time zone.
Input
No input required; it creates a Clock object based on the system's default time zone
Output
The clock is: SystemClock[Etc/UTC]
The instance is: 2019-02-07T08:54:18.679Z

Steps to obtain the current instant of the clock object

The following are the steps for obtaining the current instant of the clock object

  • Import the necessary classes Clock and Instant from the java.time package.
  • Create a Clock object using the systemDefaultZone() method.
  • Use the instant() method to get the current instant of the clock object.
  • Print the clock object and the obtained instant.

Java program to obtain the current instant of a clock

The following is an example of obtaining the current instant of a clock

import java.time.*;
public class Demo {
   public static void main(String[] args) {
      Clock c = Clock.systemDefaultZone();
      Instant i = c.instant();
      System.out.println("The clock is: " + c);
      System.out.println("The instance is: " + i);
   }
}

Output

The clock is: SystemClock[Etc/UTC]
The instance is: 2019-02-07T08:54:18.679Z

Code Explanation

In this program, the Clock object is created using the Clock.systemDefaultZone() method, gets the system clock in the default time zone. The instant() method is then used to fetch the current instant of this clock. The clock object and the instant are printed using System.out.println(). The Instant class represents a point on the timeline, and it is displayed in a standard ISO-8601 format.

Updated on: 2024-11-07T17:47:55+05:30

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements