Sub topic 11
Measuring Time-Based Amounts with Duration
A Duration is an amount of time measured in hours, minutes, seconds, and nanoseconds. It answers questions like "How long did this task take?" or "How long is this work shift?" A Duration is not tied to any date or clock. It is only a length of time, such as "2 hours and 15 minutes."
This chapter shows how to create a Duration, measure the time between two moments, read its parts, do math with it, and avoid the common mistakes.
What Duration Is For
Java has two classes for amounts of time. They measure different things:
| Class | Measures in | Good for | Example |
|---|---|---|---|
| `Duration` | hours, minutes, seconds, nanoseconds | Exact elapsed time | A 90-minute movie |
| `Period` | years, months, days | Calendar amounts | A 3-month contract |
Use Duration when you care about exact seconds. Use Period (covered in the next chapter) when you care about calendar days and months.
Creating a Duration
You can build a Duration from a single unit with the static of... methods. A static method is one you call on the class itself, not on an object.
import java.time.Duration;
public class DurationBasics {
public static void main(String[] args) {
Duration movie = Duration.ofMinutes(135);
System.out.println(movie); // PT2H15M
System.out.println(Duration.ofSeconds(90)); // PT1M30S
System.out.println(Duration.ofMillis(1500)); // PT1.5S
System.out.println(Duration.ofHours(3)); // PT3H
System.out.println(Duration.ofDays(1)); // PT24H
}
}The printed text uses the ISO-8601 format. ISO-8601 is an international standard for writing dates and times. Here is how to read it:
Pmeans "period of time." It always comes first.Tmarks the start of the time part.H,M, andSstand for hours, minutes, and seconds.
So PT2H15M means "2 hours and 15 minutes." Notice that Duration.ofDays(1) prints PT24H. A Duration stores days as hours.
You can also turn that kind of text back into a Duration with parse:
import java.time.Duration;
public class DurationParse {
public static void main(String[] args) {
Duration d = Duration.parse("PT1H30M");
System.out.println(d.toMinutes()); // 90
Duration withDays = Duration.parse("P2DT3H");
System.out.println(withDays); // PT51H
}
}Measuring Between Two Times
Duration.between(start, end) gives you the time from start to end. It works with types that have a time part, such as LocalTime, LocalDateTime, Instant, and ZonedDateTime.
import java.time.Duration;
import java.time.LocalTime;
public class ShiftLength {
public static void main(String[] args) {
LocalTime start = LocalTime.of(9, 0);
LocalTime end = LocalTime.of(17, 30);
Duration shift = Duration.between(start, end);
System.out.println(shift); // PT8H30M
Duration backwards = Duration.between(end, start);
System.out.println(backwards); // PT-8H-30M
System.out.println(backwards.isNegative()); // true
System.out.println(backwards.abs()); // PT8H30M
}
}The order of the arguments matters. If end comes before start, the result is negative. Use isNegative() to check, and abs() to get the positive length.
Timing How Long Code Takes
Instant marks a point on the timeline. Take one Instant before a task and one after it, and the Duration between them is the elapsed time.
import java.time.Duration;
import java.time.Instant;
public class Stopwatch {
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
Thread.sleep(200); // pretend to work
Instant end = Instant.now();
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toMillis() + " ms"); // about 200 ms
}
}The exact number changes a little each time you run it.
Reading the Parts of a Duration
A Duration can report its total length in different units. These to... methods return a long, which is a whole number type. Any leftover part is dropped, not rounded.
| Method | Returns for `PT2H15M` |
|---|---|
| `toHours()` | `2` |
| `toMinutes()` | `135` |
| `getSeconds()` | `8100` |
| `toMillis()` | `8100000` |
To show "2 hours 15 minutes" to a person, you need the leftover minutes. The % operator gives the remainder after division:
import java.time.Duration;
public class DurationParts {
public static void main(String[] args) {
Duration movie = Duration.ofMinutes(135);
long hours = movie.toHours(); // 2
long minutes = movie.toMinutes() % 60; // 15
System.out.println(hours + " h " + minutes + " min"); // 2 h 15 min
}
}Doing Math with Durations
A Duration is immutable, just like the other java.time types. Immutable means it never changes. Every math method returns a new Duration, so you must keep the result.
import java.time.Duration;
import java.time.LocalTime;
public class DurationMath {
public static void main(String[] args) {
Duration lesson = Duration.ofMinutes(45);
Duration withBreak = lesson.plusMinutes(10);
System.out.println(withBreak); // PT55M
Duration threeLessons = lesson.multipliedBy(3);
System.out.println(threeLessons); // PT2H15M
Duration half = lesson.dividedBy(2);
System.out.println(half); // PT22M30S
System.out.println(lesson.compareTo(half) > 0); // true
LocalTime late = LocalTime.of(23, 0);
System.out.println(late.plus(Duration.ofHours(2))); // 01:00
}
}The last line shows that LocalTime wraps around midnight. It has no date, so 23:00 plus 2 hours becomes 01:00.
Common Mistakes
Overnight times with LocalTime
LocalTime does not know about days. A night shift from 22:00 to 06:00 looks like it goes backwards:
import java.time.Duration;
import java.time.LocalTime;
public class NightShift {
public static void main(String[] args) {
LocalTime start = LocalTime.of(22, 0);
LocalTime end = LocalTime.of(6, 0);
Duration wrong = Duration.between(start, end);
System.out.println(wrong); // PT-16H
Duration fixed = wrong.isNegative() ? wrong.plusDays(1) : wrong;
System.out.println(fixed); // PT8H
}
}A better fix is to use LocalDateTime with real dates, so Java knows the shift ends on the next day.
Using Duration with LocalDate
A LocalDate has no time part, so Duration.between cannot measure seconds between two dates. This code throws an UnsupportedTemporalTypeException, which is an error raised while the program runs:
import java.time.Duration;
import java.time.LocalDate;
public class WrongType {
public static void main(String[] args) {
LocalDate a = LocalDate.of(2024, 1, 1);
LocalDate b = LocalDate.of(2024, 1, 10);
Duration d = Duration.between(a, b); // throws UnsupportedTemporalTypeException
System.out.println(d);
}
}For dates, use Period or ChronoUnit.DAYS.between, covered in the next chapters.
Exercises
Exercise
What does System.out.println(Duration.ofSeconds(3725)) print, and what do toHours() and toMinutes() return for it?
Show answer
It prints PT1H2M5S. toHours() returns 1 and toMinutes() returns 62, because the to... methods give the total in that unit and drop any remainder.
Exercise
A movie starts at LocalTime.of(20, 15) and ends at LocalTime.of(22, 40). Write one line that computes its length, and state the printed result.
Show answer
Duration length = Duration.between(LocalTime.of(20, 15), LocalTime.of(22, 40)); printing it gives PT2H25M.
Exercise
Why does Duration.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 1, 2)) fail, and what should you use instead?
Show answer
LocalDate has no time part, so it cannot be measured in seconds and nanoseconds, and Java throws UnsupportedTemporalTypeException. Use Period.between or ChronoUnit.DAYS.between for dates.
Exercise
Duration.between(LocalTime.of(23, 30), LocalTime.of(0, 15)) returns PT-23H-15M. What is the real length of this overnight gap, and how can you get it in code?
Show answer
The real gap is 45 minutes. Because the result is negative, add one day: wrong.plusDays(1) gives PT45M. Using LocalDateTime values on the correct dates also avoids the problem.