Core Java

Working with Time Using Java Instant and Long

Working with timestamps in Java usually involves a choice between high-level types (like Instant) and low-level numeric representations (like long epoch values). Each has trade-offs: Instant offers clarity, precision and immutability, while long is compact and convenient for storage or cross-system protocols. Let us delve into understanding Java time Instant and long operations with a practical example.

1. What is the Instant class in Java?

java.time.Instant (introduced in Java 8) represents a point on the UTC time-line — an instantaneous timestamp. It stores seconds and nanoseconds from the epoch (1970-01-01T00:00:00Z). Key properties:

  • Immutable and thread-safe.
  • Represents time in UTC (no timezone information attached).
  • High precision — supports nanoseconds.
  • Convenient API for arithmetic: plusSeconds, plusMillis, minus, and conversions.

Use Instant when you need readable, precise time arithmetic, or when working with the Java Time API (Durations, TemporalAdjusters, etc.). Use long for compact storage (DB columns, messaging payloads) where you store epoch seconds or milliseconds.

2. Code Example

Below is a Java example demonstrating common Instant operations: creating an instant, converting to long and back, adding/subtracting time, and computing durations.

// InstantLongExamples.java
import java.time.Duration;
import java.time.Instant;

public class InstantLongExamples {
  public static void main(String[] args) {
    // 1. Current instant
    Instant now = Instant.now();
    System.out.println("now = " + now); // e.g. 2025-08-29T10:15:30.123Z

    // 2. Convert Instant → epoch milliseconds (long)
    long epochMillis = now.toEpochMilli();
    System.out.println("epochMillis = " + epochMillis);

    // 3. Convert epoch milliseconds back to Instant
    Instant fromMillis = Instant.ofEpochMilli(epochMillis);
    System.out.println("fromMillis = " + fromMillis);

    // 4. Convert Instant → epoch seconds (long) and back
    long epochSeconds = now.getEpochSecond();
    Instant fromSeconds = Instant.ofEpochSecond(epochSeconds);
    System.out.println("epochSeconds = " + epochSeconds);

    // 5. Add and subtract time
    Instant plusFiveMinutes = now.plusSeconds(5 * 60);
    Instant minusTwoHours = now.minus(Duration.ofHours(2));
    System.out.println("plusFiveMinutes = " + plusFiveMinutes);
    System.out.println("minusTwoHours = " + minusTwoHours);

    // 6. Measure duration between two instants
    Instant earlier = now.minusSeconds(90);
    Duration duration = Duration.between(earlier, now);
    System.out.println("duration seconds = " + duration.getSeconds()); // 90

    // 7. Beware of units when storing as long
    // Decide: store epoch millis or epoch seconds. Prefer millis when you need
    // ms precision.
    // Example: persist Instant as long and restore
    long stored = now.toEpochMilli(); // store this value in DB
    // later, read 'stored' and reconstruct
    Instant restored = Instant.ofEpochMilli(stored);
    System.out.println("restored = " + restored);
  }
}

2.1 Code Explanation

This Java code demonstrates working with the Instant class and conversions to and from long values. It first gets the current moment using Instant.now() and prints it, then converts it to epoch milliseconds with toEpochMilli() and back using Instant.ofEpochMilli(). Similarly, it converts the instant to epoch seconds via getEpochSecond() and reconstructs it with Instant.ofEpochSecond(). The code also shows adding and subtracting time with plusSeconds() and minus(Duration), and measures the duration between two instants using Duration.between(). Finally, it illustrates storing an instant as a long for persistence (e.g., in a database) and restoring it later, highlighting the choice between milliseconds and seconds depending on the needed precision.

2.2 Code Run

To run this code, compile the InstantLongExamples.java file and execute it using java InstantLongExamples in your terminal or IDE.

now = 2025-08-29T10:23:47.932631199Z
epochMillis = 1756463027932
fromMillis = 2025-08-29T10:23:47.932Z
epochSeconds = 1756463027
plusFiveMinutes = 2025-08-29T10:28:47.932631199Z
minusTwoHours = 2025-08-29T08:23:47.932631199Z
duration seconds = 90
restored = 2025-08-29T10:23:47.932Z

This output demonstrates several operations performed using the Java Instant class. The now value shows the current timestamp with nanosecond precision. epochMillis converts this instant into milliseconds since the Unix epoch, while fromMillis converts it back to an Instant, showing a slight truncation to milliseconds. Similarly, epochSeconds represents the instant in seconds, and converting back with Instant.ofEpochSecond() recreates the same moment. The plusFiveMinutes and minusTwoHours examples illustrate how to add and subtract time from an instant. duration seconds measures the difference between two instants in seconds using Duration.between(). Finally, restored shows that storing an instant as epoch milliseconds and reconstructing it preserves the original timestamp, highlighting the importance of choosing the correct unit when persisting time values for applications requiring millisecond precision.

Note: Ensure you and downstream systems agree on units (seconds vs milliseconds vs nanoseconds). When using long to represent time, include metadata or field naming (e.g., createdAtMillis or createdAtSecs) to avoid confusion.

3. Conclusion

Use Instant for readability, precise time arithmetic, and integration with the java.time API. Use long for compact storage and when interacting with systems that expect epoch numbers. Always document the unit (ms/sec/nanos) and prefer Instant in application code with conversion at the system boundary (IO/DB) to keep correctness and clarity.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button