Best Way to check if a java.util.Date is older than 30 days compared to current moment in time?
Okay, assuming you really want it to be "30 days" in the default time zone, I would use something like:
// Implicitly uses system time zone and system clock
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime thirtyDaysAgo = now.plusDays(-30);
if (eventStartDate.toInstant().isBefore(thirtyDaysAgo.toInstant())) {
...
}
If "thirty days ago" was around a DST change, you need to check that the documentation for plusDays
gives you the behaviour you want:
When converting back to ZonedDateTime, if the local date-time is in an overlap, then the offset will be retained if possible, otherwise the earlier offset will be used. If in a gap, the local date-time will be adjusted forward by the length of the gap.
Alternatively you could subtract 30 "24 hour" days, which would certainly be simpler, but may give unexpected results in terms of DST changes.
You could try this:
Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
long day30 = 30l * 24 * 60 * 60 * 1000;
boolean olderThan30 = currentDate.before(new Date((eventStartDate .getTime() + day30)));
It's disguisting, but it should do the job!