Instant and Duration in Java: Points and Spans on the Time Line
How java.time models machine time: the Java time scale and leap seconds, Instant as a point counted from the epoch, Duration as exact seconds and nanoseconds, arithmetic, parsing and parts, Clock and InstantSource for testable code, and measuring elapsed time correctly.
kvi5hnuCode Sprout team member9 min readOn this page
Dates and times look simple until you need them to be right. Days have 23 or 25 hours when clocks change, months have 28 to 31 days, and the same moment has different local times around the world. Java's first attempts, java.util.Date (Java 1.0) and Calendar (Java 1.1), were mutable, error-prone and confusing. Months were counted from 0 and years from 1900. The java.time package, designed after the popular Joda-Time library and added in Java 8 (JSR 310), replaced them with immutable, thread-safe classes that make the important distinctions explicit.
Core Java I introduced LocalDate (article 29). This part covers the whole API: machine time in this article, local dates in article 68, times and time zones in article 69, and formatting, parsing and the old classes in article 70.

The Java time scale
The second used to be defined by the Earth's rotation. Since 1967 it has been defined by atomic clocks, and the Earth's rotation is slightly irregular, so official time (UTC) has occasionally inserted a leap second to stay in step with it. Leap seconds are awkward for computers. Most systems don't count them but "smear" the extra second over the surrounding hours. Leap seconds are on their way out: in 2022, the General Conference on Weights and Measures decided to allow a larger difference between atomic time and the Earth's rotation by 2035, which effectively ends them.
Java sidesteps the issue. Its time scale has exactly 86,400 seconds per day, matches official time at noon each day, and follows it closely elsewhere in a precisely defined way. Java code therefore never sees a 23:59.
Instant: a point on the time line
An Instant is a moment, counted in seconds and nanoseconds from the epoch, midnight UTC on January 1, 1970 (the same origin as Unix time). Instants can lie before the epoch (negative seconds). The range runs from about a billion years in the past (Instant.MIN) to the end of the year 1,000,000,000 (Instant.MAX).
Instant.now()reads the system clock. On current platforms its resolution is typically microseconds.Instant.ofEpochSecond(s),ofEpochSecond(s, nanos)andofEpochMilli(ms)create instants from Unix timestamps.getEpochSecond(),getNano()andtoEpochMilli()go back.Instant.parse("1969-07-20T20:17:40Z")reads ISO-8601 text, andtoString()writes it.isBefore,isAfter,compareToandequalscompare instants. They are value objects, so never use==.plus,minus,plusSeconds,plusMillisandplusNanosdo arithmetic, andtruncatedTo(ChronoUnit.MILLIS)cuts off precision. Units longer than a day, such as months, don't apply to instants and throwUnsupportedTemporalTypeException, because their length depends on a calendar and time zone.
Instants are what you store in logs, database timestamps (as TIMESTAMP WITH TIME ZONE or UTC), and wherever an event happened at one definite moment. For showing them to people, you convert them to a time zone (article 69).
Duration: an exact amount of time
A Duration is a length of time, stored as seconds (a long) plus nanoseconds. It knows nothing about calendars: a day is always exactly 24 hours.
- Creating:
Duration.ofDays,ofHours,ofMinutes,ofSeconds,ofMillis,ofNanos,Duration.between(start, end)for two instants (or two times),Duration.parse("PT2H15M"), and since Java 23instant.until(otherInstant). - Converting:
toDays,toHours,toMinutes,toSeconds,toMillis,toNanosgive the total in a unit, truncated. ThetoXxxPartmethods (Java 9) give the components: for 11 hours, 35 minutes and 30 seconds,toMinutesPart()is 35. They're useful for formatting, since there is no built-in duration formatter. - Arithmetic:
plus,minus,multipliedBy,dividedBy(long),dividedBy(Duration)(how many times one fits into another),negated,abs,truncatedTo. - Tests:
isZero,isNegative,isPositive(Java 18),compareTo.
toString and parse use the ISO-8601 format PTnHnMnS. A P starts the duration and T the time part, so PT1H30M0.25S is 1.5 hours and a quarter second. Days may appear as P2DT3H when parsing, but are normalized to hours.
Like all java.time classes, durations are immutable: plus and friends return new objects. Operations that exceed the range throw ArithmeticException. A long of nanoseconds covers about 292 years, so toNanos overflows for longer durations.
ChronoUnit offers another way to measure: ChronoUnit.MINUTES.between(a, b) counts whole units, and a.until(b, ChronoUnit.MINUTES) does the same.
Clock and InstantSource: testable time
Code that calls Instant.now() directly is hard to test. How would you check that a token expires after 15 minutes without waiting 15 minutes? Pass in a source of time instead:
InstantSource(Java 17) is a minimal interface with one abstract method,instant().InstantSource.system()reads the real clock,InstantSource.fixed(instant)always returns the same instant, andoffsetandtickderive adjusted sources.Clock(Java 8) is anInstantSourcewith a time zone, needed when code asks for local dates and times:LocalDate.now(clock),ZonedDateTime.now(clock).Clock.systemUTC(),Clock.systemDefaultZone(),Clock.fixed(instant, zone),Clock.offset(clock, duration)andClock.tick(clock, duration)(which rounds down to whole ticks) cover most needs.
Production code receives the system clock, and tests pass a fixed clock or one they can advance by hand. Every now() method in java.time has an overload that takes a Clock.
Measuring elapsed time
Duration.between(Instant.now(), ...) reads the wall clock, which can jump when the system synchronizes its time or an administrator changes it. For measuring how long something takes, use System.nanoTime(). It's monotonic, meaning it never jumps backward, and its values are meaningful only as differences: Duration.ofNanos(System.nanoTime() - start).
Even then, timing code by hand is unreliable for comparing algorithms. The JIT compiler warms up, garbage collection intervenes, and dead code gets eliminated. For benchmarks, use JMH, the Java Microbenchmark Harness.
The program
The demo works with fixed instants so that its output is always the same. It shows the epoch, a moment before it with negative epoch seconds, nanosecond precision and truncation, comparisons, arithmetic, and the exception for months. With durations, it computes a flight time and splits it into parts, then multiplies, divides, parses ISO-8601, counts whole units with ChronoUnit and overflows a duration on purpose. A TokenService takes an InstantSource, so a hand-advanced ManualClock can test token expiry without waiting. Finally the demo uses Clock.fixed, offset and tick, and measures a loop with System.nanoTime.
import java.time.*;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.util.*;
public class Solution {
// Code that needs "now" should get it from an InstantSource (or Clock), so tests can control time
record Token(String value, Instant expires) { }
static class TokenService {
private final InstantSource clock;
private final Duration lifetime;
TokenService(InstantSource clock, Duration lifetime) { this.clock = clock; this.lifetime = lifetime; }
Token issue(String value) { return new Token(value, clock.instant().plus(lifetime)); }
boolean isValid(Token t) { return clock.instant().isBefore(t.expires()); }
Duration remaining(Token t) {
Duration d = clock.instant().until(t.expires()); // Java 23; before: Duration.between(now, expires)
return d.isNegative() ? Duration.ZERO : d;
}
}
// A clock we can move forward by hand
static class ManualClock implements InstantSource {
private Instant now;
ManualClock(Instant start) { now = start; }
void advance(Duration d) { now = now.plus(d); }
@Override public Instant instant() { return now; }
}
public static void main(String[] args) {
System.out.println("--- instants ---");
Instant epoch = Instant.EPOCH;
Instant moonLanding = Instant.parse("1969-07-20T20:17:40Z");
Instant release = Instant.ofEpochSecond(1_773_100_800L); // seconds since 1970-01-01T00:00Z
System.out.println(epoch + " | " + moonLanding + " | " + release);
System.out.println("moon landing in epoch seconds: " + moonLanding.getEpochSecond() + ", millis: " + moonLanding.toEpochMilli());
Instant precise = Instant.ofEpochSecond(0, 123_456_789);
System.out.println("nanosecond precision: " + precise + ", truncated to millis: " + precise.truncatedTo(ChronoUnit.MILLIS));
System.out.println("comparisons: " + moonLanding.isBefore(epoch) + ", " + release.compareTo(epoch) + ", " + Instant.MIN + " .. " + Instant.MAX);
System.out.println("arithmetic: " + epoch.plusSeconds(90) + ", " + epoch.minus(Duration.ofDays(1)) + ", " + epoch.plus(3, ChronoUnit.HOURS));
try {
epoch.plus(1, ChronoUnit.MONTHS);
} catch (UnsupportedTemporalTypeException e) {
System.out.println("months on an Instant: " + e.getMessage());
}
System.out.println("--- durations ---");
Duration flight = Duration.between(Instant.parse("2026-11-14T08:15:00Z"), Instant.parse("2026-11-14T19:50:30Z"));
System.out.println(flight + " = " + flight.toHours() + " h " + flight.toMinutesPart() + " min " + flight.toSecondsPart() + " s"
+ " = " + flight.toMinutes() + " minutes = " + flight.toSeconds() + " seconds");
System.out.printf("formatted: %d:%02d:%02d%n", flight.toHours(), flight.toMinutesPart(), flight.toSecondsPart());
Duration d = Duration.ofHours(1).plusMinutes(30).plusMillis(250);
System.out.println(d + ", times 3: " + d.multipliedBy(3) + ", halved: " + d.dividedBy(2) + ", negated: " + d.negated());
System.out.println("how many 25-minute slots in the flight: " + flight.dividedBy(Duration.ofMinutes(25)));
System.out.println("parse: " + Duration.parse("PT2H15M") + ", " + Duration.parse("P2DT3H") + ", " + Duration.parse("-PT0.5S").toMillis() + " ms");
try {
Duration.parse("2 hours");
} catch (DateTimeParseException e) {
System.out.println("not ISO-8601: " + e.getMessage());
}
System.out.println("isZero " + Duration.ZERO.isZero() + ", isNegative " + Duration.ofSeconds(-1).isNegative()
+ ", isPositive " + Duration.ofNanos(1).isPositive());
System.out.println("between with ChronoUnit: " + ChronoUnit.MINUTES.between(epoch, epoch.plusSeconds(3599)) + " whole minutes");
System.out.println("days are exactly 24 h in a Duration: " + Duration.ofDays(1).toHours());
try {
Duration.ofSeconds(Long.MAX_VALUE).plusSeconds(1);
} catch (ArithmeticException e) {
System.out.println("overflow: " + e.getMessage());
}
System.out.println("--- clocks for testable code ---");
var clock = new ManualClock(Instant.parse("2026-11-14T09:00:00Z"));
var tokens = new TokenService(clock, Duration.ofMinutes(15));
Token t = tokens.issue("abc");
System.out.println("expires " + t.expires() + ", valid " + tokens.isValid(t) + ", remaining " + tokens.remaining(t));
clock.advance(Duration.ofMinutes(10));
System.out.println("after 10 min: valid " + tokens.isValid(t) + ", remaining " + tokens.remaining(t));
clock.advance(Duration.ofMinutes(6));
System.out.println("after 16 min: valid " + tokens.isValid(t) + ", remaining " + tokens.remaining(t));
Clock fixed = Clock.fixed(Instant.parse("2026-11-14T09:00:00Z"), ZoneOffset.UTC);
Clock later = Clock.offset(fixed, Duration.ofHours(2));
Clock ticking = Clock.tick(Clock.offset(fixed, Duration.ofMillis(1234)), Duration.ofSeconds(1));
System.out.println("fixed " + fixed.instant() + ", offset " + later.instant() + ", tick(1 s) " + ticking.instant());
System.out.println("InstantSource.fixed: " + InstantSource.fixed(Instant.EPOCH).instant());
System.out.println("--- measuring elapsed time ---");
long start = System.nanoTime(); // monotonic: use for elapsed time
long sum = 0;
for (int i = 0; i < 1_000_000; i++) sum += i;
Duration elapsed = Duration.ofNanos(System.nanoTime() - start);
System.out.println("sum " + sum + ", elapsed is positive: " + elapsed.isPositive());
}
}
--- instants ---
1970-01-01T00:00:00Z | 1969-07-20T20:17:40Z | 2026-03-10T00:00:00Z
moon landing in epoch seconds: -14182940, millis: -14182940000
nanosecond precision: 1970-01-01T00:00:00.123456789Z, truncated to millis: 1970-01-01T00:00:00.123Z
comparisons: true, 1, -1000000000-01-01T00:00:00Z .. +1000000000-12-31T23:59:59.999999999Z
arithmetic: 1970-01-01T00:01:30Z, 1969-12-31T00:00:00Z, 1970-01-01T03:00:00Z
months on an Instant: Unsupported unit: Months
--- durations ---
PT11H35M30S = 11 h 35 min 30 s = 695 minutes = 41730 seconds
formatted: 11:35:30
PT1H30M0.25S, times 3: PT4H30M0.75S, halved: PT45M0.125S, negated: PT-1H-30M-0.25S
how many 25-minute slots in the flight: 27
parse: PT2H15M, PT51H, -500 ms
not ISO-8601: Text cannot be parsed to a Duration
isZero true, isNegative true, isPositive true
between with ChronoUnit: 59 whole minutes
days are exactly 24 h in a Duration: 24
overflow: long overflow
--- clocks for testable code ---
expires 2026-11-14T09:15:00Z, valid true, remaining PT15M
after 10 min: valid true, remaining PT5M
after 16 min: valid false, remaining PT0S
fixed 2026-11-14T09:00:00Z, offset 2026-11-14T11:00:00Z, tick(1 s) 2026-11-14T09:00:01Z
InstantSource.fixed: 1970-01-01T00:00:00Z
--- measuring elapsed time ---
sum 499999500000, elapsed is positive: true
Common questions
Should I use Instant or long milliseconds?
Instant in code: it is self-describing, has nanosecond precision, and can't be confused with a duration or a count of seconds. Convert to toEpochMilli() only at boundaries that require numbers, such as some APIs, protocols or databases.
What's the difference between Duration and Period?
Duration is exact time (seconds and nanoseconds), suited to timeouts and elapsed time. Period is calendar time (years, months, days), suited to "one month later" on dates. Article 68 covers Period, and article 69 shows how they differ across daylight saving changes.
Why is Instant.now() precision only microseconds on my machine?
The precision of the system clock depends on the operating system. On most current systems, Java delivers microseconds; some offer nanoseconds. Instant itself can store nanoseconds, and truncatedTo(ChronoUnit.MILLIS) normalizes values when you need equal comparisons with data that has less precision.
Can I add a month to an Instant?
No. plus(1, ChronoUnit.MONTHS) throws UnsupportedTemporalTypeException, because the length of a month depends on the calendar and the time zone. Convert to a ZonedDateTime first.
How do I format a Duration like "1:30"?
There's no formatter for durations. Use toHoursPart(), toMinutesPart() and toSecondsPart() (Java 9) with String.format("%d:%02d:%02d", ...), or toString() for ISO format.
Should I inject Clock or InstantSource?
InstantSource (Java 17) when code needs only the current instant, which is the common case. Clock when it also needs the zone, for example to call LocalDate.now(clock). Clock implements InstantSource, so you can pass a clock either way.
API reference
| API | Purpose |
|---|---|
Instant.now(), now(clock), EPOCH, MIN, MAX | current and special instants |
Instant.ofEpochSecond, ofEpochMilli, parse, getEpochSecond, getNano, toEpochMilli | create and take apart |
isBefore, isAfter, compareTo, plus, minus, plusSeconds, truncatedTo, until | compare and compute |
Duration.ofDays, ofHours, ofMinutes, ofSeconds, ofMillis, ofNanos, between, parse | create durations |
toDays, toHours, toMinutes, toSeconds, toMillis, toNanos, toXxxPart | convert and take apart |
plus, minus, multipliedBy, dividedBy, negated, abs, isZero, isNegative, isPositive | duration arithmetic |
ChronoUnit.XXX.between(a, b), Temporal.until(end, unit) | count whole units |
Duration.MIN, MAX, Instant.plusSaturating | range helpers (Java 26) |
InstantSource.system(), fixed, offset, tick, instant() | sources of instants (Java 17) |
Clock.systemUTC(), systemDefaultZone(), fixed, offset, tick, withZone | clocks with a time zone |
System.nanoTime() | monotonic time for measuring elapsed time |
Summary
java.timereplacesDateandCalendarwith immutable classes. Its time scale has exactly 86,400 seconds per day, so leap seconds never show up.Instantis a moment counted from 1970-01-01T00 with nanosecond precision. Use it for timestamps, and convert to a zone for display.Durationis an exact amount of seconds and nanoseconds. Create it withofXxx,between,parseoruntil, and take it apart withtoXxxandtoXxxPart.- Inject a
ClockorInstantSourceinstead of callingnow()directly, so tests can control time. - Measure elapsed time with
System.nanoTime(), and benchmark with JMH.
Practice Questions
Why does Instant.now().plus(1, ChronoUnit.MONTHS) throw an exception while plus(30, ChronoUnit.DAYS) works?
An Instant has no calendar or time zone, and a month's length depends on both (28 to 31 days). Units up to DAYS have a fixed length in java.time (a day counts as 86,400 seconds), so the instant can add them. To add a calendar month, convert to a ZonedDateTime in the relevant zone, add the month there, and convert back.
How do you format a Duration of 3,725 seconds as "1:02"?
Duration d = Duration.ofSeconds(3725); String s = String.format("%d:%02d:%02d", d.toHours(), d.toMinutesPart(), d.toSecondsPart());. toHours() gives the total hours, and the Part methods give the remaining minutes and seconds.
A class checks if (Instant.now().isAfter(deadline)). How do you make it testable?
Give the class an InstantSource (or Clock) field, set through the constructor, and call source.instant() instead of Instant.now(). Production code passes InstantSource.system(), and tests pass InstantSource.fixed(...) or a hand-advanceable implementation to check behavior before and after the deadline.
Why is System.nanoTime() better than Instant.now() for timing a method call?
Instant.now() follows the wall clock, which can jump forward or backward when the system clock is adjusted, for example by NTP synchronization, giving wrong or even negative elapsed times. System.nanoTime() is monotonic and intended for measuring intervals. Its absolute value is meaningless, but differences are reliable.
What does Duration.parse("P1DT12H").toHours() return, and what does that tell you about days in a Duration?
- A duration's day is always exactly 24 hours, so "P1DT12H" means 36 hours. If you need calendar days, which can have 23 or 25 hours across a daylight saving change, use a
Periodtogether with dates or zoned date-times (articles 68 and 69).
Previous: Connection Pools, DataSources and JPA: JDBC in Real Applications
Related reading
- Connection Pools, DataSources and JPA: JDBC in Real Applications
- JDBC Transactions: Commit, Rollback, Isolation, Save Points and Batch Updates
- JDBC Metadata: DatabaseMetaData, ResultSetMetaData and ParameterMetaData
- JDBC Row Sets: CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet
- Scrollable and Updatable Result Sets in JDBC

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.