
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 zoneOutput
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.Advertisements