Java 如何确定ZonedDateTime是否为;今天;?
我以为这会被问到,但我找不到 使用Java 如何确定ZonedDateTime是否为;今天;?,java,java-time,Java,Java Time,我以为这会被问到,但我找不到 使用java.time确定给定的ZoneDateTime是否为“今天”的最佳方法是什么 我至少想出了两种可能的解决办法。我不确定这些方法是否存在漏洞或陷阱。基本上,我们的想法是让java.time算出它,而不是自己做任何数学运算: /** * @param zonedDateTime a zoned date time to compare with "now". * @return true if zonedDateTime is "today". * Wh
java.time
确定给定的ZoneDateTime
是否为“今天”的最佳方法是什么
我至少想出了两种可能的解决办法。我不确定这些方法是否存在漏洞或陷阱。基本上,我们的想法是让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;
}
如果您的意思是今天在默认时区:
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()));
如果您的意思是今天与ZoneDateTime位于同一时区:
return zonedDateTime.toLocalDate().equals(LocalDate.now(zonedDateTime.getZone()));
您是在询问值的时区中是“今天”,还是JVM的默认时区中?您不应该说ZonedDateTime now=ZonedDateTime.now()。它始终是当天的日期。意思是永远都是今天。首先,要明确你所说的“今天”是什么意思!但是默认区域中的
now()
日期可能与值区域中的日期不同。@Andreas键入得太快了-谢谢。我相信op的示例也使用了默认时区。作为一种好的风格,我建议在第一个示例中使用ZoneId.systemDefault()
,否则我会认为这是一个错误,并且您打算在第二个示例中使用ZoneDateTime
中的时区。