How to determine if ZonedDateTime is "today"?

tir38 :

I assumed this would have already been asked, but I couldn't find anything.

Using java.time what is the best way to determine if a given ZonedDateTime is "today"?

I've come up with at least two possible solutions. I'm not sure if there are any loopholes or pitfalls with these approaches. Basically the idea is to let java.time figure it out and not do any math myself:

/**
 * @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;
}
assylias :

If you mean today in the default time zone:

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

If you mean today in the same timezone as the ZonedDateTime:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=445018&siteId=1