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;
}
now() now() method of a ZonedDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return ZonedDateTime based on system clock with default time-zone to obtain the current date-time. The zone and offset will be set based on the time-zone in the clock.
If you want the last second of the day, you can use: ZonedDateTime eod = zonedDateTime. with(LocalTime. of(23, 59, 59));
A ZonedDateTime represents a date-time with a time offset and/or a time zone in the ISO-8601 calendar system. On its own, ZonedDateTime only supports specifying time offsets such as UTC or UTC+02:00 , plus the SYSTEM time zone ID.
ZonedDateTime describes a date-time with a time zone in the ISO-8601 calendar system (such as 2007-12-03T10:15:30+01:00 Europe/Paris ). OffsetDateTime describes a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system (such as 2007-12-03T10:15:30+01:00 ).
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With