Codectionary / Developer documentation / Java

Elapsed Time with Duration

Duration measures an amount of time in seconds and nanoseconds. Unlike a calendar period, a duration day is exactly 24 hours. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

Duration.between(startInstant, endInstant); duration.toMinutes()

Examples

Elapsed Time with Duration

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.time.Duration;
import java.time.Instant;

public class Main {
  public static void main(String[] args) throws Exception {
    Instant start = Instant.parse("2024-01-01T10:00:00Z");
    Instant end = Instant.parse("2024-01-01T11:30:00Z");
    Duration elapsed = Duration.between(start, end);
    System.out.println(elapsed.toMinutes());
    System.out.println(elapsed);
  }
}
  1. Expected output: 90 PT1H30M
  2. The instants differ by ninety minutes. The default representation uses ISO-8601 duration notation.

Best practices

  • Use System.nanoTime differences for measuring local execution time.
  • Use Period or calendar date arithmetic for months and years.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading