In this post I am going to show you EXACTLY how to work with Instant class in Java.
Instant class is a part of java.time
package.
Instant class is designed to represent specific point in time with nanosecond precision in coordinated universal time (UTC).
It does not depends on any time zone
Creating Instant
To create an instant class you can use Instant.now()
method to obtain current timestamp without any timezone information
Let us check with an example
|
|
Output is:
|
|
From the above output you can see it does not depends upon any timezone
Creating Instant
from ofEpochSecond method
You can create Instant from Unix timestamp which is nothing but number of seconds since Unix epoch, January 1, 1970
In the below example we have number no of seconds after January 1,1970
We can use Instant.ofEpochSecond()
method and pass number of seconds as arguments to get Instant object.
|
|
Output is:
|
|
Creating Instant
using string in ISO-8601 format.
Instant.parse()
is used to create an Instant object from a string representation of a timestamp.
This string must be in the ISO-8601 format.
If the string is not in the correct format, a DateTimeParseException will be thrown.
|
|
Manipulating Instant
You can perform operations like adding and subtracting time using plus and minus method.
|
|
|
|
Converting Instant
to ZonedDateTime
You can combine Instant with a timezone to get instant at specific timezone. In the below example we have converted
Instant to “Asia/Kolkata” timezone using atZone
method of Instant
class.
|
|
|
|
Conclusion
Thus,Java’s instant class can be used for handling timestamps and managing time-related operations with precision. It can be used in wide range of applications like logging and measuring execution times for it’s accuracy.