如何判断 ZonedDateTime 是否为 "today"?

How to determine if ZonedDateTime is "today"?

我以为已经有人问过这个问题了,但我找不到 anything

使用 java.time 确定给定 ZonedDateTime 是否为 "today" 的最佳方法是什么?

我想出了至少两种可能的解决方案。我不确定这些方法是否存在任何漏洞或陷阱。基本上,我的想法是让 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()));

如果您是说今天与 ZonedDateTime 在同一时区:

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