2017-04-18 2 views
4

이미 질문을 받았을 것이라고 가정했지만 anything을 찾을 수 없습니다.ZonedDateTime이 "오늘"인지 확인하는 방법은 무엇입니까?

java.time을 사용하면 주어진 ZonedDateTime이 "오늘"인지 확인하는 가장 좋은 방법은 무엇입니까?

적어도 두 가지 가능한 해결책을 생각해 냈습니다. 이러한 접근법을 사용하는 허점이나 함정이 있는지 확실하지 않습니다.

/** 
* @param zonedDateTime a zoned date time to compare with "now". 
* @return true if zonedDateTime is "today". 
* Where today is defined as year, month, and day of month being equal. 
*/ 
public static boolean isZonedDateTimeToday1(ZonedDateTime zonedDateTime) { 
    ZonedDateTime now = ZonedDateTime.now(); 

    return now.getYear() == zonedDateTime.getYear() 
      && now.getMonth() == zonedDateTime.getMonth() 
      && now.getDayOfMonth() == zonedDateTime.getDayOfMonth(); 
} 


/** 
* @param zonedDateTime a zoned date time to compare with "now". 
* @return true if zonedDateTime is "today". 
* Where today is defined as atStartOfDay() being equal. 
*/ 
public static boolean isZoneDateTimeToday2(ZonedDateTime zonedDateTime) { 
    ZonedDateTime now = ZonedDateTime.now(); 
    LocalDateTime atStartOfToday = now.toLocalDate().atStartOfDay(); 

    LocalDateTime atStartOfDay = zonedDateTime.toLocalDate().atStartOfDay(); 

    return atStartOfDay == atStartOfToday; 
} 
+1

값의 시간대가 "오늘"이거나 JVM의 기본 시간대 인 값을 묻는 중입니까? – Andreas

+0

ZonedDateTime now = ZonedDateTime.now()라고 말하면 안됩니다. 그것은 항상 현재 날짜입니다. 항상 오늘을 의미합니다. – Sedrick

+0

먼저 "오늘"이 의미하는 바를 절대적으로 분명하게 말하십시오! – slim

답변

7

기본 시간대 오늘을 의미하는 경우 :

return zonedDateTime.toLocalDate().equals(LocalDate.now()); 

//you may want to clarify your intent by explicitly setting the time zone: 
return zonedDateTime.toLocalDate().equals(LocalDate.now(ZoneId.systemDefault())); 

를 같은 시간대로 오늘을 의미하는 경우 기본적 아이디어는 java.time 그림 그것을 밖으로가 아니라 어떤 수학을 자신 할 수 있도록하는 것입니다 ZonedDateTime :

return zonedDateTime.toLocalDate().equals(LocalDate.now(zonedDateTime.getZone())); 
+0

그러나 기본 영역의'now()'는 값 영역의 날짜와 다른 날짜 일 수 있습니다. – Andreas

+0

@Andreas가 너무 빨리 입력되었습니다. - 감사합니다. op의 예에서도 기본 시간대를 사용한다고 생각합니다. – assylias

+3

좋은 스타일로, 처음에는'ZoneId.systemDefault()'를 사용하는 것이 좋을 것입니다. 그렇지 않으면 실수 였다고 생각할 것이고, 두 번째처럼'ZonedDateTime'에서 존을 사용하려고합니다. 하나. – JodaStephen

관련 문제