[Java] Period와 Duration 클래스

sseongeun·2024년 8월 27일

Duration 클래스와 Period 클래스는 둘다 Time 패키지에 속한 클래스이지만,
목적은 다르다!

1) Duration
Duration은 두 시간 간의 차이를 계산하여 출력해주는 클래스이다.

LocalTime start = LocalTime.of(8, 41, 30); //시,분,초
LocalTime end = LocalTime.of(8, 42, 50, 700); //시,분,초,nano단위 초

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

System.out.println(duration.getSeconds()); //80
System.out.println(duration.getNano()); //700

2) Period
Period는 두 일자 간의 차이를 계산하여 출력해주는 클래스이다.

LocalDate startDate = LocalDate.of(2000, 9, 1);
LocalDate endDate = LocalDate.of(2006, 9, 2);

Period period = Period.between(startDate, endDate);

System.out.println("Years: " + period.getYears()); //6
System.out.println("Months: " + period.getMonths()); //0
System.out.println("Days: " + period.getDays()); //1

참고로, 년도가 달라도, getMonths()는 오직 월단위의 차이만을 계산하여 반환해준다.

profile
공부 기록...

0개의 댓글