Date & Time API
Period and Duration
Measure date-based (Period) vs time-based (Duration) intervals.
Interview: Tests the difference between Period and Duration, and choosing the correct representation for calendar calculations.
The Java Date-Time API represents time intervals using two distinct types: Period (date-based: years, months, days) and Duration (time-based: seconds, nanoseconds).
Core Idea
Period measures intervals on the calendar. Duration measures physical time on the timeline.
Why It Matters
Applying Duration to calendar dates can introduce errors due to daylight saving adjustments or leap years.
Interview Lens
Tests explaining differences between Period and Duration, and applying them in calculations.
Period vs. Duration
Period: Focuses on date concepts (e.g.2 years, 3 months, 12 days). Used withLocalDate.Duration: Focuses on precise machine time (e.g.48 hours, 30 minutes). Used withLocalTimeorInstant.
Code Walkthrough
This program demonstrates calculating intervals using both Period and Duration.
import java.time.LocalDate; import java.time.Instant; import java.time.Period; import java.time.Duration;public class IntervalDemo { public static void main(String[] args) throws InterruptedException { // 1. Period calculation LocalDate bday = LocalDate.of(1995, 10, 25); LocalDate now = LocalDate.now(); Period age = Period.between(bday, now); System.out.println("Age: " + age.getYears() + " years");
// 2. Duration calculation Instant start = Instant.now(); Thread.sleep(500); // Simulate execution delay Instant end = Instant.now(); Duration elapsed = Duration.between(start, end); System.out.println("Elapsed: " + elapsed.toMillis() + " ms"); } }
Interview-Relevant Information
Q: What happens if you try to calculate a Duration between two LocalDate instances?
Answer: It throws an UnsupportedTemporalTypeException. Because LocalDate contains no time metrics (hours, minutes), the JVM cannot calculate duration in seconds. To calculate intervals between local dates, you must use Period.
Quick Checklist
Which class represents date-based intervals? Can you calculate Duration on LocalDate? If yes, you understand Period and Duration.
Use Cases
Calculating user age based on date of birth records.
Monitoring transaction timeouts in asynchronous systems.
Common Mistakes
Using Duration to model calendar days where DST changes occur (DST days can be 23 or 25 hours long, making a fixed 24-hour duration inaccurate).
Calling getDays() on Duration and expecting it to convert total hours to days (it only returns the day component; use toDays() instead).