반응형
LocalDate 인스턴스를 비교하는 방법 Java 8
날짜가 매우 정확해야하는 앱을 작성 중이며 LocalDate 인스턴스를 어떻게 비교할 수 있는지 궁금합니다. 지금은 다음과 같은 것을 사용했습니다.
LocalDate localdate1 = LocalDate().now();
LocalDate localdate2 = someService.getSomeDate();
localdate1.equals(localdate2);
하지만 내 앱이 나에게 혼란스러운 결과를주는 것을 발견했고, 날짜 비교 때문이라고 생각합니다.
오랜만에 1970 년대부터 시간을 구하고 비교 해볼까 생각하고 있는데, 좀 더 쉬울 것 같네요.
사용하면 다음과 같습니다.equals() LocalDate
int compareTo0(LocalDate otherDate) {
int cmp = (year - otherDate.year);
if (cmp == 0) {
cmp = (month - otherDate.month);
if (cmp == 0) {
cmp = (day - otherDate.day);
}
}
return cmp;
}
의 결과가 마음에 들지 않으면 equals()의 미리 정의 된 방법을 사용하는 것이 좋습니다 LocalDate.
이러한 모든 메서드가 메서드를 사용하고 compareTo0()있으며 cmp값만 확인하십시오 . 여전히 이상한 결과가 나오면 (그렇게해서는 안됩니다) 입력 및 출력의 예를 첨부하세요.
LocalDate ld ....;
LocalDateTime ldtime ...;
ld.isEqual(LocalDate.from(ldtime));
이 스 니펫은 날짜 비교가 두 개 이상의 항목에 걸쳐있는 상황에서도 도움이 될 것이라고 생각합니다.
static final int COMPARE_EARLIEST = 0;
static final int COMPARE_MOST_RECENT = 1;
public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) {
LocalDate refDate = null;
switch(comparatorType)
{
case COMPARE_EARLIEST:
//returns the most earliest of the date entries
refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
case COMPARE_MOST_RECENT:
//returns the most recent of the date entries
refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
}
return refDate;
}
참고 URL : https://stackoverflow.com/questions/29201103/how-to-compare-localdate-instances-java-8
반응형
'Nice programing' 카테고리의 다른 글
| NSDictionaryOfVariableBindings 신속하게 대응합니까? (0) | 2020.12.01 |
|---|---|
| 동일한 폴더에 go 파일 가져 오기 (0) | 2020.12.01 |
| RSA 개인 키 암호는 내부에서 어떻게 작동합니까? (0) | 2020.12.01 |
| 언제 IORef를 사용해도 괜찮습니까? (0) | 2020.12.01 |
| 자바 스크립트로 현재 페이지의 모든 쿠키를 나열하려면 어떻게해야합니까? (0) | 2020.12.01 |