In Java, the Instant
class is a part of the java.time
package and represents a specific point in time with nanosecond precision. It is used to represent a moment on the timeline in the ISO-8601 calendar system, with the same meaning as the ZonedDateTime
class, but without any time zone information.
An Instant
object can be created using the ofEpochMilli()
or ofEpochSecond()
factory methods, which take the number of milliseconds or seconds since the epoch (midnight, January 1, 1970 UTC) as an argument. For example:
Instant instant = Instant.ofEpochMilli(1592608000000L); // 2020-06-23T00:00:00Z
The Instant
class also provides methods for comparing, formatting, and parsing Instant
objects, as well as for converting them to other date and time types.
For example, you can use the format()
method to convert an Instant
object to a formatted string:
Instant instant = Instant.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String formatted = instant.format(formatter); // e.g. "2022-12-22T15:38:34.123Z"
You can also use the atZone()
method to convert an Instant
object to a ZonedDateTime
object in a specific time zone:
Instant instant = Instant.now(); ZonedDateTime zoned = instant.atZone(ZoneId.of("Europe/Paris"));
For more information on the Instant
class in Java, you can refer to the Java documentation.