728x90
반응형
compareTo를 통한 날짜 비교
▷ Example
public void testDateCompare() {
// 테스트 데이터 생성
String strTestDate1 = "20210504153300";
String strTestDate2 = "20210505153300";
String strTestDate3 = "20210505153300";
try {
// 형 변환
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date testDate1 = format.parse(strTestDate1);
Date testDate2 = format.parse(strTestDate2);
Date testDate3 = format.parse(strTestDate3);
// 변환된 값 확인
System.out.println("testDate1 : " + testDate1);
System.out.println("testDate2 : " + testDate2);
System.out.println("testDate3 : " + testDate3);
/* 날짜 비교 */
int compare1 = testDate1.compareTo(testDate2); // -1
System.out.println("testDate1 > testDate2 : " + compare1);
int compare2 = testDate2.compareTo(testDate1); // 1
System.out.println("testDate2 > testDate1 : " + compare2);
int compare3 = testDate2.compareTo(testDate3); // 0
System.out.println("testDate2 == testDate3 : " + compare3);
} catch (ParseException e) {
System.out.println("Error : " + e);
}
}
/*
결과 :
testDate1 : Tue May 04 15:33:00 KST 2021
testDate2 : Wed May 05 15:33:00 KST 2021
testDate3 : Wed May 05 15:33:00 KST 2021
testDate1 > testDate2 : -1
testDate2 > testDate1 : 1
testDate2 == testDate3 : 0
*/
728x90
728x90
'▶ Back-End > Java' 카테고리의 다른 글
파일 생성하기 (0) | 2021.05.13 |
---|---|
파일 검색 후 파일 읽기 (0) | 2021.05.13 |
JSON 응답 필드 Null 값 제외(@JsonInclude) (0) | 2021.04.30 |
해당 월 말일 산출 (0) | 2021.04.23 |
문자열 중간 마스킹 처리 (0) | 2021.04.22 |
댓글