Adding Duration and Period to Temporal Objects
What you'll learn: How to combine Duration and Period with temporal objects to perform date and time calculations.
Now that you understand Duration and Period, it's time to apply them. The beauty of Java's Date and Time API is that temporal objects like LocalDate, LocalTime, LocalDateTime, ZonedDateTime, and Instant can work seamlessly with these temporal amounts using plus() and minus() methods.
The Core Principle: Match the Type
Duration works with time-based types (those containing time components):
LocalTimeLocalDateTimeZonedDateTimeInstant
Period works with date-based types (those containing date components):
LocalDateLocalDateTimeZonedDateTime
Notice that LocalDateTime and ZonedDateTime accept both because they contain both date and time!
Adding Duration to Time-Based Types
LocalTime morning = LocalTime.of(9, 30);
Duration twoHours = Duration.ofHours(2);
LocalTime later = morning.plus(twoHours); // 11:30
Instant now = Instant.now();
Duration thirtyMinutes = Duration.ofMinutes(30);
Instant future = now.plus(thirtyMinutes);
Adding Period to Date-Based Types
LocalDate today = LocalDate.of(2024, 1, 15);
Period oneMonth = Period.ofMonths(1);
LocalDate nextMonth = today.plus(oneMonth); // 2024-02-15
Period threeWeeks = Period.ofWeeks(3);
LocalDate later = today.minus(threeWeeks); // 2023-12-25
Working with LocalDateTime and ZonedDateTime
LocalDateTime meeting = LocalDateTime.of(2024, 3, 15, 14, 0);
meeting = meeting.plus(Period.ofDays(7)); // Move one week forward
meeting = meeting.plus(Duration.ofHours(2)); // Push back 2 hours
Key Takeaway: Apply Duration to time-based temporal objects and Period to date-based ones using plus() and minus() methods—types that contain both date and time accept both temporal amounts.