YouTip LogoYouTip

Java Instant Class

The Instant class is an important class in the date and time API introduced in Java 8 (java.time package), representing an instantaneous point on the timeline. This class is primarily used for recording timestamps, precise to the nanosecond level. The Instant class has the following main characteristics: * Represents time starting from 1970-01-01T00:00:00Z (Unix epoch) * Does not contain timezone information * Is immutable and thread-safe * Precise to nanoseconds (whereas the traditional Date class is only precise to milliseconds) * * * ## Creating Instant Objects ### Getting Current Time ## Example Instant now = Instant.now();// Get current time ### Creating from Epoch Time ## Example Instant instant1 = Instant.ofEpochSecond(3);// 1970-01-01T00:00:03Z Instant instant2 = Instant.ofEpochSecond(3, 0);// Same as above Instant instant3 = Instant.ofEpochSecond(2, 1 _000_000_000);// 1 nanosecond after 3 seconds Instant instant4 = Instant.ofEpochSecond(4, -1 _000_000_000);// 1 nanosecond before 3 seconds ### Creating from Milliseconds ## Example Instant instant = Instant.ofEpochMilli(1000);// 1970-01-01T00:00:01Z * * * ## Common Methods of Instant Class ### Getting Time Information ## Example Instant instant = Instant.now(); long seconds = instant.getEpochSecond();// Get seconds since 1970-01-01 int nanos = instant.getNano();// Get nanosecond portion ### Time Comparison ## Example Instant instant1 = Instant.now(); Instant instant2 = instant1.plusSeconds(10); boolean isBefore = instant1.isBefore(instant2);// true boolean isAfter = instant1.isAfter(instant2);// false ### Time Arithmetic ## Example Instant instant = Instant.now(); // Add 10 seconds Instant later = instant.plusSeconds(10); // Subtract 5 minutes Instant earlier = instant.minus(Duration.ofMinutes(5)); // Add 2 days 4 hours 30 minutes Instant future = instant.plus(2, ChronoUnit.DAYS) .plus(4, ChronoUnit.HOURS) .plus(30, ChronoUnit.MINUTES); * * * ## Converting Instant to Other Date-Time Classes ### Instant and LocalDateTime ## Example Instant instant = Instant.now(); // Instant to LocalDateTime LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // LocalDateTime to Instant Instant fromLdt = ldt.toInstant(ZoneOffset.UTC); ### Instant and ZonedDateTime ## Example Instant instant = Instant.now(); // Instant to ZonedDateTime ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Shanghai")); // ZonedDateTime to Instant Instant fromZdt = zdt.toInstant(); ### Instant and Date ## Example // Instant to Date Date date =Date.from(instant); // Date to Instant Instant fromDate = date.toInstant(); * * * ## Practical Applications of Instant Class ### Recording Event Timestamps ## Example public class Event{ private String name; private Instant timestamp; public Event(String name){ this.name= name; this.timestamp= Instant.now(); } // getters... } ### Calculating Time Intervals ## Example Instant start = Instant.now(); // Perform some operations... Instant end = Instant.now(); Duration duration = Duration.between(start, end); System.out.println("Operation duration: "+ duration.toMillis()+" milliseconds"); ### Scheduled Tasks ## Example Instant now = Instant.now(); Instant nextRun = now.plus(1, ChronoUnit.HOURS); while(Instant.now().isBefore(nextRun)){ // Wait until specified time try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } } // Execute scheduled task System.out.println("Scheduled task execution time: "+ Instant.now()); ### Comprehensive Example ## Example import java.time.Instant; import java.time.Duration; import java.time.temporal.ChronoUnit; public class InstantExample { public static void main(String[] args){ // 1. Get Instant of current time Instant now = Instant.now(); System.out.println("Current time: "+ now); // 2. Parse Instant from string Instant parsedInstant = Instant.parse("2023-05-15T10:15:30.00Z"); System.out.println("Parsed Instant: "+ parsedInstant); // 3. Create specific Instant Instant epochInstant = Instant.ofEpochSecond(0); System.out.println("Epoch time (1970-01-01T00:00:00Z): "+ epochInstant); Instant specificInstant = Instant.ofEpochSecond(1684131330); System.out.println("Specific timestamp: "+ specificInstant); // 4. Time arithmetic Instant later = now.plusSeconds(60);// Add 60 seconds System.out.println("60 seconds later: "+ later); Instant earlier = now.minus(2, ChronoUnit.HOURS);// Subtract 2 hours System.out.println("2 hours ago: "+ earlier); // 5. Calculate time interval Duration duration = Duration.between(earlier, later); System.out.println("Time interval: "+ duration.toMinutes()+" minutes"); // 6. Compare times System.out.println("Is earlier before later: "+ earlier.isBefore(later)); System.out.println("Is later after earlier: "+ later.isAfter(earlier)); // 7. Get timestamp System.out.println("Seconds since epoch: "+ now.getEpochSecond()); System.out.println("Nanosecond portion: "+ now.getNano()); } } The output is similar to: Current time: 2025-05-01T03:19:09.345806ZParsed Instant: 2023-05-15T10:15:30ZEpoch time (1970-01-01T00:00:00Z): 1970-01-01T00:00:00ZSpecific timestamp: 2023-05-15T06:15:30Z60 seconds later: 2025-05-01T03:20:09.345806Z2 hours ago: 2025-05-01T01:19:09.345806ZTime interval: 121 minutes Is earlier before later: true Later is after earlier: true Seconds since epoch: 1746069549Nanosecond portion: 345806000 * * * ## Notes on Instant Class 1. **Timezone Issue**: Instant does not contain timezone information; it always represents UTC time. If you
← Java Duration ClassJava Localtime Class β†’