如何确定ZonedDateTime是否是"今天"?

时间:2017-04-18 15:10:19

标签: java java-time

我认为这已经被问过,但我找不到anything

使用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;
}

1 个答案:

答案 0 :(得分:9)

如果您今天在默认时区:

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()));