Course contentsShow
← Java
Lesson 1899 of 2,87038. Date and Time API (java.time)Free lesson

Replacing Calendar Arithmetic with Period and Duration

Migrating date calculations from Calendar.add() to immutable Period and Duration operations.

Replacing Calendar Arithmetic with Period and Duration

What you'll learn: How to migrate mutable Calendar.add() operations to clean, immutable date calculations using Period and Duration.

The Old Way: Calendar Arithmetic

In legacy code, you might see date calculations using Calendar.add() or Calendar.roll():

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 5);  // Adds 5 days - mutates calendar!
cal.add(Calendar.HOUR, -3);         // Subtracts 3 hours - more mutation
Date result = cal.getTime();        // Extract result

This approach has problems: mutability (the calendar object changes), verbosity (multiple method calls), and fragility (easy to forget what state the calendar is in).

The Modern Way: Period and Duration

The java.time API offers immutable arithmetic. Use Period for date-based amounts (days, months, years) and Duration for time-based amounts (hours, minutes, seconds):

LocalDate today = LocalDate.now();
LocalDate fiveDaysLater = today.plus(Period.ofDays(5));  // Returns new object

LocalDateTime now = LocalDateTime.now();
LocalDateTime threeHoursAgo = now.minus(Duration.ofHours(3));  // Returns new object

Why It's Better

Immutability: Each operation returns a new object; the original is unchanged. Think of it like arithmetic with numbers: 5 + 3 doesn't change 5.

Clarity: Period.ofDays(5) is self-documenting. Compare with Calendar.DAY_OF_MONTH constants.

Chainability: Since methods return new objects, you can chain operations cleanly:

LocalDate future = today
    .plus(Period.ofMonths(2))
    .plus(Period.ofDays(10));

Type Safety: Period only works with date-based types, Duration with time-based types—no mixing time and date units incorrectly.

Key Takeaway: Replace mutable Calendar.add() arithmetic with immutable plus() and minus() operations using Period (for dates) and Duration (for times)—your code becomes safer, clearer, and more maintainable.