Period.between() 두 날짜 사이 비교

이승주·2024년 4월 3일
0

과거 대학 입학 날짜 2016년 3월 2일 ~ 졸업 날인 2024년 2월 20일
사이 기간을 알아 보고 싶다면 어떻게 해야 할까?

두 날짜 사이의 차이를 계산을 도와주는 Period.between() 을 사용하여 알 수 있다.


LocalDateTime

LocalDateTime은 날짜 데이터와 시간 데이터를 가지는 클래스다.
(LocalDate는 날짜만 저장)

두 LocalDateTime 인스턴스의 차이를 구하는 메서드는 존재하지 않아 위에서 언급한 Period.between()를 사용한다.


Period 와 Duration

Period.between()

사용 예제

LocalDate startDate = LocalDate.of(1939, 9, 1);
LocalDate endDate = LocalDate.of(1945, 9, 2);

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

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

결과

Years: 6
Months: 0
Days: 1

두 LocalDateTime 인스턴스 사이의 년, 월, 일 차이를 구하기 위해서는 Period 클래스의 between() 메서드를 사용

Period.between() 메서드 특징

  • 두 날짜 사이의 간격을 년/월/일 단위로 반환한다.
  • "x년 y개월 z일" 형식의 데이터가 반환된다. 따라서, getDays() 메서드를 호출하면 두 날짜 사이의 일수가 아닌 "z일" 부분만 반환된다.
    • getYears()
    • getMonths()
    • getDays()

Duration.between()

사용 예제

LocalTime start = LocalTime.of(10, 35, 40);
//10시 35분 40초
LocalTime end = LocalTime.of(10, 36, 50, 800);
//10시 36분 50초 800나노초
Duration duration = Duration.between(start, end);

System.out.println("Seconds: " + duration.getSeconds());
System.out.println("Nano Seconds: " + duration.getNano());

결과

Seconds: 70
Nano Seconds: 800
  • 두 시간 사이의 간격을 초나 나노 초 단위단위로 반환한다.
  • getSeconds() 사용시 초, getNano() 나노초 반환

Period로 사이 기간 구하기

1.  LocalDateTime을 LocalDate로 변환

만약 날짜를 LocalDateTime형식으로 받는다면 시간 데이터는 분리한다.

xxxx년x월 ~xxxx년x월 사이에 기간을 구분해야 하기 때문에 시간 데이터는 필요 없다. 따라서 toLocalDate() 사용

사용 예시

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
System.out.println(localDateTime.toLocalDate());

결과

2021-11-08T12:42:11.769062
2021-11-08

2. Period.between() 사용 하기

사용 예시

LocalDateTime registerAt = user.getRegisterAt();
 LocalDateTime nowRegisterAt = LocalDateTime.now();
 
 Period diff = Period.between(registerAt.toLocalDate(), nowRegisterAt.toLocalDate());
 

  System.out.printf("두 날짜 사이 기간: %d년 %d월 %d일",
          diff.getYears(), diff.getMonths(), diff.getDays());

diff.getYears(), diff.getMonths(), diff.getDays())메소드는 int형으로 반환 됨

결과

두 날짜 사이 기간: 1822

결과

System.out.println(diff);
P1Y8M22D

참고 자료

https://covenant.tistory.com/255

https://www.daleseo.com/java8-duration-period/

남궁성-자바의정석 P528~541

profile
반복되는 실수를 기록을 통해 줄여가보자!

0개의 댓글

관련 채용 정보