Sub topic 11
Measuring Time-Based Amounts with Duration
Sometimes you need to know how long something lasts, such as a meeting, a download, or a race. A Duration is a java.time class that holds an amount of time counted in hours, minutes, seconds, and nanoseconds. It does not belong to any date or time zone. It only says "how much time."
Creating a Duration
You can build a Duration directly from a number. A factory method is a static method that creates an object for you, so you don't call new.
import java.time.Duration;
public class MakeDuration {
public static void main(String[] args) {
Duration a = Duration.ofMinutes(135);
Duration b = Duration.ofSeconds(90);
Duration c = Duration.ofHours(2).plusMinutes(15);
System.out.println(a); // PT2H15M
System.out.println(b); // PT1M30S
System.out.println(a.equals(c)); // true
System.out.println(a.toHours()); // 2
}
}The printed text follows the ISO-8601 format, a world standard for writing dates and times. PT2H15M means "Period of Time: 2 hours, 15 minutes." Notice that toHours() returns only whole hours, so the leftover 15 minutes are dropped.
Measuring Between Two Times
Duration.between finds the time between two moments. It works with LocalTime, LocalDateTime, and Instant.
import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
public class Between {
public static void main(String[] args) {
LocalTime start = LocalTime.of(9, 15);
LocalTime end = LocalTime.of(11, 30);
Duration meeting = Duration.between(start, end);
System.out.println(meeting); // PT2H15M
System.out.println(meeting.toMinutes()); // 135
Duration backwards = Duration.between(end, start);
System.out.println(backwards); // PT-2H-15M
System.out.println(backwards.isNegative()); // true
Instant t1 = Instant.parse("2024-01-01T10:00:00Z");
Instant t2 = Instant.parse("2024-01-01T10:00:05.5Z");
System.out.println(Duration.between(t1, t2).toMillis()); // 5500
}
}If the second argument comes earlier than the first, the result is negative.
Doing Math with Durations
A Duration is immutable, which means it never changes after it is created. Methods like plusMinutes return a new Duration. You must keep that new value.
| Method | What it does | Example result |
|---|---|---|
| `plusMinutes(30)` | Adds 30 minutes | `PT2H15M` becomes `PT2H45M` |
| `minusSeconds(60)` | Subtracts 60 seconds | `PT1M30S` becomes `PT30S` |
| `multipliedBy(2)` | Doubles the amount | `PT45M` becomes `PT1H30M` |
| `toSeconds()` | Total seconds (Java 9+) | `PT2M` gives `120` |
| `getSeconds()` | Total seconds (Java 8+) | `PT2M` gives `120` |
Exercise
What does Duration.ofHours(3).plusMinutes(20).toMinutes() return?
Show answer
200. Three hours is 180 minutes, and adding 20 gives 200.
Exercise
A race starts at LocalTime.of(14, 0) and ends at LocalTime.of(13, 45). What does Duration.between(start, end) print, and why?
Show answer
It prints PT-15M. The end time is earlier than the start time, so the Duration is negative.