我認爲這已經被問過了,但我找不到anything。如何確定ZonedDateTime是否爲「今天」?
使用java.time
確定給定的ZonedDateTime
是否爲「今天」的最佳方法是什麼?
我已經想出了至少兩種可能的解決方案。我不確定這些方法是否存在漏洞或陷阱。基本想法是讓java.time
數字出來,並沒有做任何的數學自己:
/**
* @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;
}
你問的值是「今天」的值的時區或JVM的默認時區? – Andreas
你不應該說ZonedDateTime now = ZonedDateTime.now()。它始終是當天的日期。意味着它永遠是今天。 – Sedrick
首先,明確「今日」的含義! – slim