java.time.InstantSource Class in Java
Last Updated :
08 Apr, 2023
The java.time.Instant class in Java basically represents a point in time. It is a precise moment on the timeline of the Unix epoch. The Unix epoch is the time 00:00:00 UTC on 1 January 1970. The Instant class can be used to represent timestamps, durations, and intervals.
Instant values can be obtained from various sources including the clock time, network time, and database time. The Instant.now() is the method that returns the current instant from the system clock. This is useful for obtaining the current timestamp.
Example of obtaining the current timestamp using Instant.now()
Java
import java.time.Instant;
public class InstantExample {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println( "Current timestamp: " + now);
}
}
|
Output:
Current timestamp: 2023-04-03T12:32:34.243715Z
In the addition to the Instant.now(), there are other ways to create Instant objects. For example, you can parse a string that represents an instant using the Instant.parse() method. Here’s an example:
Java
import java.time.Instant;
public class InstantExample {
public static void main(String[] args) {
Instant instant = Instant.parse( "2023-04-03T12:32:34.243715Z" );
System.out.println( "Parsed timestamp: " + instant);
}
}
|
Output:
Parsed timestamp: 2023-04-03T12:32:34.243715Z
You can also create an Instant object from a java.util.Date object using the Date.toInstant() method. Here’s an example:
Java
import java.time.Instant;
import java.util.Date;
public class InstantExample {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println( "Instant from Date: " + instant);
}
}
|
Output:
Instant from Date: 2023-04-03T12:32:34.244891Z
Instant objects are immutable, meaning that once an Instant object is created, its value not going to be changed. However, you can create a new Instant object based on an existing Instant object by using methods such as Instant.plus() and Instant.minus(). These methods return a new Instant object that is adjusted by the specified amount of time. For example:
Java
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class InstantExample {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println( "Current timestamp: " + now);
Instant oneHourLater = now.plus( 1 , ChronoUnit.HOURS);
System.out.println( "One hour later: " + oneHourLater);
Instant thirtySecondsEarlier = now.minus( 30 , ChronoUnit.SECONDS);
System.out.println( "Thirty seconds earlier: " + thirtySecondsEarlier);
}
}
|
Output:
Current timestamp: 2023-04-03T12:32:34.245917Z
One hour later: 2023-04-03T13:32:34.
Share your thoughts in the comments
Please Login to comment...