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);
}
}- Expected output: 90 PT1H30M
- 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