Skip to main content
Advertisement

10.2 Date Arithmetic and Period, Duration

Now that you know how to fetch dates, let's master adding and subtracting dates, and calculating the difference between two dates. The java.time package equips you with powerful tools precisely designed for this.

1. Adding & Subtracting Dates/Times (plus, minus Methods)

LocalDate and LocalDateTime objects are Immutable, meaning every time you modify a date, it ** returns a brand new object**instead of modifying the existing one. Remember: it's NOT like this.date = date + 5 days!

import java.time.LocalDate;

LocalDate today = LocalDate.now(); // 2026-03-13

// 30 days from now
LocalDate after30Days = today.plusDays(30);
System.out.println("30 Days Later: " + after30Days); // 2026-04-12

// 2 months ago
LocalDate before2Months = today.minusMonths(2);
System.out.println("2 Months Ago: " + before2Months); // 2026-01-13

// 1 year from now
LocalDate nextYear = today.plusYears(1);
System.out.println("Next Year: " + nextYear); // 2027-03-13

Key plus/minus methods:

  • plusDays(long) / minusDays(long): Add/subtract in day units
  • plusMonths(long) / minusMonths(long): Add/subtract in month units
  • plusYears(long) / minusYears(long): Add/subtract in year units
  • plusHours(long) / plusMinutes(long): For LocalDateTime in hour/minute units (not available on date-only types)

2. Interval Between Two Dates: Period

To calculate "how many years, months, and days" separate two dates, use the Period class.

import java.time.LocalDate;
import java.time.Period;

LocalDate birthDate = LocalDate.of(1995, 6, 15);
LocalDate today = LocalDate.of(2026, 3, 13);

// Period.between(startDate, endDate)
Period p = Period.between(birthDate, today);

System.out.println("Age: " + p.getYears() + " years"); // 30 years
System.out.println("Months: " + p.getMonths() + " months"); // 8 months
System.out.println("Days: " + p.getDays() + " days"); // 26 days

3. Interval Between Two Times: Duration

To calculate "how many seconds or minutes" separate two time values, use the Duration class, which measures time in seconds or milliseconds.

import java.time.LocalTime;
import java.time.Duration;

LocalTime start = LocalTime.of(10, 30, 0); // 10:30:00 AM
LocalTime end = LocalTime.of(14, 15, 30); // 02:15:30 PM

Duration d = Duration.between(start, end);

System.out.println("Difference (seconds): " + d.getSeconds()); // 13530 seconds
System.out.println("Difference (minutes): " + d.toMinutes() + " min"); // 225 minutes
System.out.println("Difference (hours): " + d.toHours() + " hrs"); // 3 hours

Quick Summary:

  • Date ↔ Date arithmetic → Period(in years, months, days)
  • Time ↔ Time arithmetic → Duration(in seconds, milliseconds)
Advertisement