Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java negative Duration fields: seconds and nanos are normalized

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A negative Duration stores a signed seconds field and a nonnegative nanosecond adjustment, so its components can surprise callers.

Compare the whole duration

A duration of negative 1.5 seconds is represented as seconds -2 plus 500 million nanos. Printing getSeconds and getNano separately can look contradictory if the reader assumes both components share a sign. Use toMillis, compareTo, or the whole value when making a deadline decision.

The fixture prints the components and the total milliseconds. Expiry checks should compare Instants directly when the business rule is before or after a deadline.

Keep unit conversion explicit

Conversions to whole units can discard a fractional remainder. A negative duration close to zero needs careful treatment if a UI displays rounded seconds or an API accepts integer milliseconds. Do not make a retry decision from a rounded display value.

Working program

Java
import java.time.Duration;

public class RetryDelayDebt {
    public static void main(String[] args) {
        Duration overdue = Duration.ofMillis(-1500);
        System.out.println(overdue.getSeconds());
        System.out.println(overdue.getNano());
        System.out.println(overdue.toMillis());
        System.out.println(overdue.isNegative());
    }
}

Output

Output
-2
500000000
-1500
true

Cost and ownership

Duration is a fixed-size immutable value, and these conversions use constant application work. The failure risk is interpreting one component as the signed total or truncating a fractional duration before a boundary comparison.

Common Mistakes

  • Do not infer the total sign from getNano.
  • Do not rebuild a negative duration by giving both fields the same sign.
  • Do not round a deadline interval before deciding whether work is overdue.

Read next

Java Duration versus Period across a daylight-saving change, Java Clock: test expiry without sleeping, Java date and time: local schedules versus instants, Java Instant toEpochMilli: detect lost submillisecond precision.

java
time
duration-negative-components
Storage details