Best way to check if java.util.Date is older than 30 days compared to current time?

Here is 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 use Java 8, Calendar is not preferred.

Time Zone: ZoneId.systemDefault ().

+4
source share
2 answers

Well, if you really want the default time zone to be “30 days,” 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 plusDaysgives you the behavior you want:

ZonedDateTime, - , , , . - .

30 "24-" , , , , DST.

+6

:

Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
long day30 = 30l * 24 * 60 * 60 * 1000;
boolean olderThan30 = currentDate.before(new Date((eventStartDate .getTime() + day30)));

, !

+3

All Articles