Period and Duration
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer's age is "18 years, 6 months", while a delivery takes "3 hours 15 minutes". Different questions about time need different tools.
Two kinds of gap
A Period is an amount of time in years, months and days; a Duration is an exact amount of time in seconds and nanoseconds.
A gap in time is measured in one of two ways: in calendar units or in exact clock time. "Rohan is 18 years old" uses the calendar: years and months, whose lengths change.
import java.time.*;
public class TwoGaps { public static void main(String[] args) { Period age = Period.between(LocalDate.of(2005, 8, 20), LocalDate.of(2024, 3, 15)); Duration exam = Duration.ofHours(3).plusMinutes(15); System.out.println(age); System.out.println(exam); System.out.println(age.getYears() + " years, " + exam.toMinutes() + " minutes"); }}P18Y6M24D PT3H15M 18 years, 195 minutes
"The exam lasts 3 hours" uses clock time: an hour is always 60 minutes.
A month is not a fixed number of seconds. February has 28 or 29 days, March has 31. So Java keeps the two ideas apart. Period stores years, months and days for dates. Duration stores seconds and nanoseconds for times.
The old way was to subtract milliseconds and divide by 1000, 60, 60 and 24. That breaks for months, and it is easy to get one of the divisions wrong. java.time does the counting for you.
Period: forLocalDatevalues. Age, notice period, membership length.Duration: for times and date-times. Exam length, ride time, server response time.ChronoUnit.X.between: one total number in any unit, such as days or minutes.
Period: age from a date of birth
Period.between(start, end) returns the gap as years, months and days. Read the parts with getYears(), getMonths() and getDays(). For age, Period.between(dob, today).getYears() is all you need.
Example 1 · Age from a date of birth
import java.time.LocalDate;import java.time.Period;
public class AgeDemo { public static void main(String[] args) { LocalDate dob = LocalDate.of(2005, 8, 20); LocalDate onDate = LocalDate.of(2024, 3, 15); // in a real app: LocalDate.now()
int wrongAge = onDate.getYear() - dob.getYear(); Period p = Period.between(dob, onDate);
System.out.println("Year subtraction: " + wrongAge); System.out.println("Period: " + p); System.out.println("Age: " + p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days");
LocalDate birthday = LocalDate.of(2024, 8, 20); System.out.println("Age on birthday: " + Period.between(dob, birthday).getYears()); }}Year subtraction: 19 Period: P18Y6M24D Age: 18 years, 6 months, 24 days Age on birthday: 19
What this code does
- 2024 minus 2005 is 19, but the birthday in August has not come yet on 15 March.
Period.betweenchecks the month and day, so the real age is 18. - The period prints as
P18Y6M24D. On the birthday itself the age becomes 19.
Example 2 · Building and adding periods
import java.time.LocalDate;import java.time.Period;
public class NoticePeriodDemo { public static void main(String[] args) { LocalDate resigned = LocalDate.of(2024, 1, 15); Period notice = Period.ofMonths(3); Period course = Period.of(1, 6, 0);
System.out.println("Notice: " + notice); System.out.println("Last day: " + resigned.plus(notice)); System.out.println("Course: " + course); System.out.println("Course ends: " + LocalDate.of(2024, 7, 1).plus(course)); System.out.println("Ten days: " + Period.ofDays(10)); System.out.println("Gap: " + Period.between(LocalDate.of(2024, 1, 31), LocalDate.of(2024, 3, 1))); }}Notice: P3M Last day: 2024-04-15 Course: P1Y6M Course ends: 2026-01-01 Ten days: P10D Gap: P1M1D
What this code does
Period.ofMonths(3)andPeriod.of(1, 6, 0)build periods directly, anddate.plus(period)adds them with the same month-end rule asplusMonths.- From 31 January to 1 March is
P1M1D: one month brings you to 29 February (the last valid day), and one more day reaches 1 March.
The tempting shortcut, today.getYear() - dob.getYear(), is wrong until the birthday has passed in the current year. Period checks the month and day for you. You can also build a period, such as Period.ofDays(10), Period.ofMonths(3) or Period.of(1, 6, 0), and add it with date.plus(period). A period prints in ISO-8601 form, the standard text format for dates and gaps: P18Y6M24D means 18 years, 6 months and 24 days.
Duration: hours, minutes and seconds
Duration.between(start, end) works on LocalTime, LocalDateTime and other time-based values. An exam from 10:00 to 13:15 gives PT3H15M: the T marks the start of the time part.
Example 3 · Exam length with Duration
import java.time.Duration;import java.time.LocalDateTime;import java.time.LocalTime;
public class ExamLengthDemo { public static void main(String[] args) { LocalTime start = LocalTime.of(10, 0); LocalTime end = LocalTime.of(13, 15); Duration exam = Duration.between(start, end);
System.out.println("Duration: " + exam); System.out.println("Total minutes: " + exam.toMinutes()); System.out.println("Total hours: " + exam.toHours()); System.out.println("Display: " + exam.toHoursPart() + "h " + exam.toMinutesPart() + "m"); System.out.println("Same as 195 min? " + exam.equals(Duration.ofMinutes(195)));
LocalDateTime shiftStart = LocalDateTime.of(2024, 3, 15, 22, 0); LocalDateTime shiftEnd = LocalDateTime.of(2024, 3, 16, 6, 30); System.out.println("Night shift: " + Duration.between(shiftStart, shiftEnd)); System.out.println("Backwards negative? " + Duration.between(end, start).isNegative()); }}Duration: PT3H15M Total minutes: 195 Total hours: 3 Display: 3h 15m Same as 195 min? true Night shift: PT8H30M Backwards negative? true
What this code does
toMinutes()is the total (195) andtoHours()is whole hours only (3).toHoursPart()andtoMinutesPart()split the duration for a display like "3h 15m".LocalDateTimevalues can cross midnight, so the night shift correctly lastsPT8H30M. Swapping start and end gives a negative duration.
toMinutes() and toHours() give the total in that unit. toHoursPart() and toMinutesPart() give one part of a clock-style display, so 195 minutes reads as 3 hours and 15 minutes. Build one with Duration.ofMinutes(195) or Duration.ofHours(3). If the end is before the start, the duration is negative; isNegative() checks that. Duration.between on two LocalDate values throws UnsupportedTemporalTypeException, because a plain date has no seconds to count.
ChronoUnit.DAYS.between, and the getDays trap
ChronoUnit.DAYS.between(a, b) returns a long with the total number of days from a to b. The start day is counted and the end day is not, so 10 March to 11 March is 1 day.
Example 4 · Trap: Period.getDays is not the total
import java.time.LocalDate;import java.time.Period;import java.time.temporal.ChronoUnit;
public class TotalDaysDemo { public static void main(String[] args) { LocalDate start = LocalDate.of(2024, 1, 10); LocalDate end = LocalDate.of(2024, 3, 15);
Period p = Period.between(start, end); System.out.println("Period: " + p); System.out.println("p.getDays(): " + p.getDays()); System.out.println("DAYS.between: " + ChronoUnit.DAYS.between(start, end)); System.out.println("WEEKS.between: " + ChronoUnit.WEEKS.between(start, end)); System.out.println("MONTHS.between: " + ChronoUnit.MONTHS.between(start, end)); System.out.println("start.until(DAYS): " + start.until(end, ChronoUnit.DAYS)); System.out.println("Next day: " + ChronoUnit.DAYS.between(end, end.plusDays(1))); }}Period: P2M5D p.getDays(): 5 DAYS.between: 65 WEEKS.between: 9 MONTHS.between: 2 start.until(DAYS): 65 Next day: 1
What this code does
getDays()returns only the days part ofP2M5D, which is 5. The real gap is 65 days: 21 left in January, 29 in February and 15 in March.WEEKSandMONTHScount whole units only, so 65 days is 9 weeks and 2 months. The end day is not counted, so one day to the next is 1.
Example 5 · Wrong tool: Duration between two dates
import java.time.Duration;import java.time.LocalDate;import java.time.temporal.ChronoUnit;import java.time.temporal.UnsupportedTemporalTypeException;
public class DurationDatesDemo { public static void main(String[] args) { LocalDate a = LocalDate.of(2024, 3, 1); LocalDate b = LocalDate.of(2024, 3, 15); try { System.out.println(Duration.between(a, b)); } catch (UnsupportedTemporalTypeException e) { System.out.println("Duration failed: " + e.getMessage()); } System.out.println("Days: " + ChronoUnit.DAYS.between(a, b)); System.out.println("Hours: " + Duration.between(a.atStartOfDay(), b.atStartOfDay()).toHours()); }}Duration failed: Unsupported unit: Seconds Days: 14 Hours: 336
What this code does
Durationcounts seconds, and aLocalDatehas none, soDuration.betweenon two dates throwsUnsupportedTemporalTypeException.- For days between dates, use
ChronoUnit.DAYS.between. If you really need hours, turn the dates into date-times first withatStartOfDay().
WEEKS, MONTHS, YEARS, HOURS and MINUTES work the same way and count only whole units.
Here is the classic trap. From 10 January to 15 March 2024, Period.between gives P2M5D: 2 months and 5 days. getDays() returns 5, only the days part. The total is 65 days. When you need "how many days", use ChronoUnit.DAYS.between, never Period.getDays().
Fix the error
Fix the gap calculation
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
A library counts the overdue days between two dates.
Error
Overdue.java:9: error: incompatible types: long cannot be converted to Period
Period late = ChronoUnit.DAYS.between(due, returned);
^a.until(b, ChronoUnit.DAYS) is the same as ChronoUnit.DAYS.between(a, b).Real-world use: overdue days and a library fine
A library charges Rs. 2 for each day a book is late, with a maximum fine of Rs. 100. The overdue days are ChronoUnit.DAYS.between(due, returned). If the book comes back early, that number is negative, so clamp it to zero with Math.max(0, days).
Example 6 · Library fine for overdue books
import java.time.LocalDate;import java.time.temporal.ChronoUnit;
public class LibraryFineDemo { static final int FINE_PER_DAY = 2; static final int MAX_FINE = 100;
static long overdueDays(LocalDate due, LocalDate returned) { return Math.max(0, ChronoUnit.DAYS.between(due, returned)); }
static long fine(LocalDate due, LocalDate returned) { return Math.min(MAX_FINE, overdueDays(due, returned) * FINE_PER_DAY); }
public static void main(String[] args) { LocalDate due = LocalDate.of(2024, 3, 29); String[] returns = {"2024-03-25", "2024-03-29", "2024-04-02", "2024-05-20"}; for (String r : returns) { LocalDate returned = LocalDate.parse(r); System.out.println("Returned " + returned + ": " + overdueDays(due, returned) + " days late, fine Rs. " + fine(due, returned)); } }}Returned 2024-03-25: 0 days late, fine Rs. 0 Returned 2024-03-29: 0 days late, fine Rs. 0 Returned 2024-04-02: 4 days late, fine Rs. 8 Returned 2024-05-20: 52 days late, fine Rs. 100
What this code does
- An early return gives a negative day count, and
Math.max(0, ...)turns it into 0 days late. Returning on the due date is also 0 days late. - Four days late costs Rs. 8. The May return is 52 days late, which would be Rs. 104, so
Math.mincaps it at Rs. 100.
The same pattern fits many apps: days of delay for a delivery, days left until an exam, the number of hours a parking slot was used. Pick the unit, count with between, then apply the business rule.
Next step
Check your understanding
12 quick questions