과거 대학 입학 날짜 2016년 3월 2일 ~ 졸업 날인 2024년 2월 20일
사이 기간을 알아 보고 싶다면 어떻게 해야 할까?
두 날짜 사이의 차이를 계산을 도와주는 Period.between() 을 사용하여 알 수 있다.
LocalDateTime은 날짜 데이터와 시간 데이터를 가지는 클래스다.
(LocalDate는 날짜만 저장)
두 LocalDateTime 인스턴스의 차이를 구하는 메서드는 존재하지 않아 위에서 언급한 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() 메서드 특징
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()
나노초 반환만약 날짜를 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
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형으로 반환 됨
두 날짜 사이 기간: 1년 8월 22일
System.out.println(diff);
P1Y8M22D
https://covenant.tistory.com/255
https://www.daleseo.com/java8-duration-period/
남궁성-자바의정석 P528~541