Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

compare

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

like image 450
Steve Waters Avatar asked Mar 25 '15 10:03

Steve Waters


2 Answers

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.

like image 189
Jon Skeet Avatar answered Nov 15 '22 17:11

Jon Skeet


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!

like image 39
gaRos Avatar answered Nov 15 '22 15:11

gaRos