10.2 날짜 연산과 Period, Duration
날짜를 가져오는 법을 배웠으니 이제 날짜끼리 더하거나 빼거나, 두 날짜 사이의 차이를 계산하는 법 을 알아봅니다. java.time 패키지에는 이를 위한 강력한 도구들이 마련되어 있습니다.
1. 날짜/시간 더하고 빼기 (plus, minus 메서드)
LocalDate, LocalDateTime 객체는 불변(Immutable) 이므로, 날짜를 바꿀 때마다 새 객체를 반환 합니다. this.date = date + 5일 같은 개념이 아니라는 것을 기억하세요!
import java.time.LocalDate;
LocalDate today = LocalDate.now(); // 2026-03-13
// 30일 뒤
LocalDate after30Days = today.plusDays(30);
System.out.println("30일 뒤: " + after30Days); // 2026-04-12
// 2개월 전
LocalDate before2Months = today.minusMonths(2);
System.out.println("2개월 전: " + before2Months); // 2026-01-13
// 1년 뒤
LocalDate nextYear = today.plusYears(1);
System.out.println("내년: " + nextYear); // 2027-03-13
주요 plus/minus 메서드:
plusDays(long)/minusDays(long): 일(Day) 단위로 더하고 빼기plusMonths(long)/minusMonths(long): 월(Month) 단위로 더하고 빼기plusYears(long)/minusYears(long): 연(Year) 단위로 더하고 빼기plusHours(long)/plusMinutes(long):LocalDateTime에서 시간/분 단위 (날짜엔 없음)
2. 두 날짜 사이의 간격: Period
두 날짜 사이에 "몇 년, 몇 달, 며칠이 차이나는지"를 계산할 때는 Period 클래스를 씁니다.
import java.time.LocalDate;
import java.time.Period;
LocalDate birthDate = LocalDate.of(1995, 6, 15);
LocalDate today = LocalDate.of(2026, 3, 13);
// Period.between(시작날짜, 끝날짜)
Period p = Period.between(birthDate, today);
System.out.println("나이: " + p.getYears() + "세"); // 30세
System.out.println("개월: " + p.getMonths() + "개월"); // 8개월
System.out.println("일: " + p.getDays() + "일"); // 26일
3. 두 시간 사이의 간격: Duration
두 시각 사이에 "몇 초, 몇 분이 차이나는지"를 초(second) 또는 밀리초 단위로 계산할 때는 Duration 클래스를 씁니다.
import java.time.LocalTime;
import java.time.Duration;
LocalTime start = LocalTime.of(10, 30, 0); // 오전 10:30:00
LocalTime end = LocalTime.of(14, 15, 30); // 오후 02:15:30
Duration d = Duration.between(start, end);
System.out.println("차이 (초): " + d.getSeconds()); // 13530초
System.out.println("차이 (분): " + d.toMinutes() + "분"); // 225분
System.out.println("차이 (시): " + d.toHours() + "시간"); // 3시간
요약 정리:
- 날짜 + 날짜 연산 →
Period(년, 월, 일 단위)- 시간 + 시간 연산 →
Duration(초, 밀리초 단위)