Best Way to check if a java.util.Date is older than 30 days compared to current moment in time?

Here's what I want to do:

Date currentDate = new Date();
Date eventStartDate = event.getStartDate();

How to check if eventStartDate is more than 30 days older than currentDate?

I'm using Java 8, Calendar isn't preferred.

Time zone is ZoneId.systemDefault().

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow