Course contentsShow
← Java
Lesson 1832 of 2,87038. Date and Time API (java.time)Free lesson

Nanosecond Precision: getNano() and ofEpochSecond(long, long)

Access nanosecond components and create Instants with nanosecond-level precision beyond milliseconds.

Nanosecond Precision: getNano() and ofEpochSecond(long, long)

What You'll Learn

You'll learn how to work with nanosecond-level precision in Instant objects, going beyond millisecond accuracy for high-resolution timestamps.

Understanding Nanosecond Precision

An Instant stores time as two components: whole seconds since the epoch and a nanosecond adjustment within that second (0-999,999,999). While methods like toEpochMilli() give you millisecond precision, Java's time API actually tracks time down to the nanosecond level—that's one billionth of a second.

Think of it like measuring distance: if seconds are miles, milliseconds are feet, but nanoseconds are the width of a human hair. For high-frequency trading, scientific measurements, or precise logging, this level of detail matters.

Accessing Nanoseconds with getNano()

The getNano() method returns the nanosecond portion within the current second:

Instant instant = Instant.parse("2024-01-15T10:30:45.123456789Z");

long seconds = instant.getEpochSecond();  // 1705318245
int nanos = instant.getNano();             // 123456789

System.out.println("Seconds: " + seconds);
System.out.println("Nanoseconds within that second: " + nanos);

Important: getNano() doesn't return total nanoseconds since epoch—just the sub-second fraction.

Creating Instants with Nanosecond Precision

The two-parameter ofEpochSecond(long epochSecond, long nanoAdjustment) lets you specify nanoseconds explicitly:

// Create instant at exactly 100 seconds + 500 million nanoseconds (0.5 sec)
Instant precise = Instant.ofEpochSecond(100, 500_000_000);
System.out.println(precise.getNano());  // 500000000

// Nanosecond overflow automatically adjusts seconds
Instant overflow = Instant.ofEpochSecond(100, 1_500_000_000);  // 1.5 billion nanos
System.out.println(overflow.getEpochSecond());  // 101 (rolled over)
System.out.println(overflow.getNano());          // 500000000

Key Takeaway: Use getNano() to access sub-second precision and ofEpochSecond(long, long) to create Instant objects with nanosecond accuracy—essential for applications requiring timing precision beyond milliseconds.