简体   繁体   中英

Best way to compare two dates in Java (day criteria)?

I would like to know the best way to compare two Dates in Java , such as in this following scenario:

Date date = new Date(time);
Date now = new Date();
//
long day = 86400000L;
long days = day * 7;
if ((date.getTime() + days) <= now.getTime()) {
     // DO 1
} else {
     // DO 2
}

In other words: I would like to get a Date object, add in some days and compare them.

Question: Is there a good solution for Java 6? And for Java 8 (using the new Time API)? I would like to use the Date.after(Date date) and Date.before(Date date) for this (after adding the days to a Date)

Thank you!

EDIT

Looks like this can be done, according to Coffee. I dont know if there's a better way.

Calendar date = Calendar.getInstance();
date.setTime(new Date(time));
date.add(Calendar.DATE, 7);
Calendar now = Calendar.getInstance();
//
if(now.after(date)) {
     // DO 1
} else {
     // DO 2
}

You can use Joda-Time and make your life a quite a bit easier:

DateTime dt = new  DateTime(time);
if (dt.plusDays(7).isBeforeNow()) {
 // DO 1
} else {
 // DO 2
}

In Java 8:

LocalDate date = LocalDate.ofEpochDay(time); // days!
if (date.plusDays(7).isBefore(LocalDate.now())) {
    // DO 1
} else {
    // DO 2
}

If time is in millis:

Date d = new Date();
d.setTime(time);
LocalDate date = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Explanation is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM