날짜 차이 계산하기
이번 포스팅은 두 날짜 사이의 차이를 계산하는 방법을 소개합니다.
LocalDateTime 차이 계산
LocalDateTime 클래스는 날짜 데이터와 시간 데이터를 가지는 클래스입니다. 따라서, 두 LocalDateTime 인스턴스의 차이를 구하는 메서드는 존재하지 않으며 두 LocalDateTime 인스턴스의 차이를 구하기 위해서는 LocalDate와 LocalTime을 분리해야 합니다.
날짜 및 시간을 분리하기 위해 LocalDateTime 클래스에서 제공하는 메서드를 사용합니다.
toLocalDate()
- 날짜 데이터를 가져옵니다.
toLocalTime()
- 시간 데이터를 가져옵니다.
다음 예제는 LocalDateTime 인스턴스에서 toLocalDate() 및 toLocalTime() 메서드를 호출합니다.
public static void main(String args[]) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 8, 1, 14, 30, 55);
System.out.println("localDateTime.toLocalDate()");
System.out.println(localDateTime.toLocalDate());
System.out.println("\nlocalDateTime.toLocalTime()");
System.out.println(localDateTime.toLocalTime());
}
[실행 결과]
localDateTime.toLocalDate()
2020-08-01
localDateTime.toLocalTime()
14:30:55
년, 월, 일 차이 구하기
두 LocalDateTime 인스턴스 사이의 년, 월, 일 차이를 구하기 위해서는 Period 클래스의 between() 메서드를 사용합니다.
Period.between() 메서드 특징
- 시작 날짜는 포함되지만 종료 날짜는 제외됩니다.
- "x년 y개월 z일" 형식의 데이터가 반환됩니다. 따라서, getDays() 메서드를 호출하면 두 날짜 사이의 일수가 아닌 "z일" 부분만 반환됩니다.
다음 예제는 Period 클래스의 between() 메서드를 호출하여 두 날짜 사이의 기간을 구합니다.
public static void main(String args[]) {
LocalDateTime startDT = LocalDateTime.of(2019, 11, 10, 18, 40, 25);
LocalDateTime endDT = LocalDateTime.of(2021, 8, 1, 14, 30, 55);
System.out.println("시작일: " + startDT.toLocalDate());
System.out.println("종료일: " + endDT.toLocalDate());
Period diff = Period.between(startDT.toLocalDate(), endDT.toLocalDate());
System.out.printf("두 날짜 사이 기간: %d년 %d월 %d일",
diff.getYears(), diff.getMonths(), diff.getDays());
}
[실행 결과]
시작일: 2019-11-10
종료일: 2021-08-01
두 날짜 사이 기간: 1년 8월 22일
시간, 분, 초 차이 구하기
두 LocalDateTime 인스턴스 사이의 시, 분, 초 차이를 구하기 위해서는 Duration 클래스의 between() 메서드를 사용합니다.
Duration.between() 특징
- 두 시간 사이를 초(second)로 계산합니다.
- toHours(), toMinutes(), toMillis() 메서드는 두 시간 사이의 초(second)가 시간, 분, 밀리초로 계산된 값입니다.
- 시작 시간이 종료 일자보다 이후인 경우 음수가 반환됩니다.
다음 예제는 Duration 클래스의 between() 메서드를 호출하여 두 시간 사이를 가져옵니다.
public static void main(String args[]) {
LocalDateTime startDT = LocalDateTime.of(2019, 11, 10, 10, 40, 25);
LocalDateTime endDT = LocalDateTime.of(2021, 8, 1, 14, 30, 55);
System.out.println("시작시간: " + startDT.toLocalTime());
System.out.println("종료시간: " + endDT.toLocalTime());
Duration diff = Duration.between(startDT.toLocalTime(), endDT.toLocalTime());
System.out.printf("시간: %d, 분: %d, 초: %d, 밀리초: %d, 나노초: %d",
diff.toHours(), diff.toMinutes(), diff.getSeconds(), diff.toMillis(), diff.getNano());
}
[실행 결과]
시작시간: 10:40:25
종료시간: 14:30:55
시간: 3, 분: 230, 초: 13830, 밀리초: 13830000, 나노초: 0
Calendar 및 Date 차이 계산
Calendar 및 Date 타입의 두 인스턴스에서 날짜 차이를 계산하는 방법입니다.
계산 방법
1. Calendar 인스턴스를 getTime() 메서드를 사용하여 Date 타입으로 변환합니다.
2. getTime() 메서드는 날짜를 밀리초로 반환하므로 두 Date 인스턴스 사이의 밀리초를 계산합니다.
3. 계산된 밀리초를 사용하여 년 / 일 / 시간 / 분 / 초를 계산합니다.
4. 월마다 일 수가 다르므로 월은 구할 수 없습니다.
public static void main(String args[]) {
Calendar startCalendar = new GregorianCalendar(2019, 11, 10, 10, 40, 25);
Date startDT = startCalendar.getTime();
System.out.printf("%d년 %d월 %d일 %d:%d:%d\n",
startDT.getYear(), startDT.getMonth(), startDT.getDate(),
startDT.getHours(), startDT.getMinutes(), startDT.getSeconds());
Calendar endCalendar = new GregorianCalendar(2021, 5, 1, 20, 20, 55);
Date endDT = endCalendar.getTime();
System.out.printf("%d년 %d월 %d일 %d:%d:%d",
endDT.getYear(), endDT.getMonth(), endDT.getDate(),
endDT.getHours(), endDT.getMinutes(), endDT.getSeconds());
long differenceInMillis = endDT.getTime() - startDT.getTime();
long years = (differenceInMillis / (365 * 24 * 60 * 60 * 1000L));
long days = (differenceInMillis / (24 * 60 * 60 * 1000L)) % 365;
long hours = (differenceInMillis / (60 * 60 * 1000L)) % 24;
long minutes = (differenceInMillis / (60 * 1000L)) % 60;
long seconds = (differenceInMillis / 1000) % 60;
System.out.printf("\n두 날짜 사이: %d년 %d일 %d:%d:%d",
years, days, hours, minutes, seconds);
}
[실행 결과]
119년 11월 10일 10:40:25
121년 5월 1일 20:20:55
두 날짜 사이: 1년 174일 9:40:30
'Java' 카테고리의 다른 글
[Java]날짜 더하기 및 빼기(LocalDate 더하기 및 빼기) (0) | 2022.08.13 |
---|---|
[Java]LocalTime 비교 방법(시간 비교 방법) (0) | 2022.08.12 |
[Java]날짜 정렬 방법 (0) | 2022.08.11 |
[Java]LocalDate 비교 방법(날짜 비교 방법) (0) | 2022.08.11 |
[Java]폴더(디렉토리) 생성 방법 (0) | 2022.07.12 |
댓글