Duration and Period
- Java course
- Advanced
- Lesson 21/82
- 5 min
Learn spans with Duration and Period.
Duration vs Period
Duration and Period both represent a length of time, but with different units. Duration is hour-minute-second based; Period is year-month-day based.
Example: Duration.between(start, end) gives the length between two times in hours and minutes. Period.between(birth, today) gives the age between two dates in years, months and days. Using the wrong type produces odd results; that is why you pick Period for dates and Duration for times.
Date ranges with Period
Period expresses year-month-day based ranges. It can be created with methods like Period.ofYears(1) or Period.ofMonths(6); you can also take the difference between two dates with Period.between.
Example: LocalDate next = today.plus(Period.ofYears(1)). This adds one year to today. Passing a Period to plus gives the same result as calling plusYears(1); but it is more flexible when you want to carry the range as a variable.
Practice Find the duration between two times
Create two times: LocalTime.of(10, 0) and LocalTime.of(12, 30). Print the minutes between them using Duration.between(start, end).toMinutes() with System.out.println.
Starter code
import java.time.Duration;
import java.time.LocalTime;
// Create two LocalTimes: 10:00 and 12:30
// Find the duration with Duration.between
// Print the minutes with toMinutesSample solution
import java.time.Duration;
import java.time.LocalTime;
public class DurationExample {
public static void main(String[] args) {
LocalTime start = LocalTime.of(10, 0);
LocalTime end = LocalTime.of(12, 30);
System.out.println(Duration.between(start, end).toMinutes());
}
}Expected output
150
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which class holds an hour-minute based length of time?
- Duration Correct answer
- Period
- LocalDate
- Instant
Explanation: Duration is hour-minute-second based.
2 Complete the Duration.between call
Duration d = Duration.____(start, end);
Duration d = Duration.between(start, end);
Explanation: between gives the length between two times.
3 Match the Duration and Period methods
| Term | Meaning |
|---|---|
Duration |
Hour based |
Period |
Day based |
between |
Between two times |
ofDays |
Make with days |