Reputation: 357
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
}
Upvotes: 0
Views: 236
Reputation: 2510
In Java 8:
LocalDate date = LocalDate.ofEpochDay(time); // days!
if (date.plusDays(7).isBefore(LocalDate.now())) {
// DO 1
} else {
// DO 2
}
EDIT
If time is in millis:
Date d = new Date();
d.setTime(time);
LocalDate date = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Explanation is here.
Upvotes: 2
Reputation: 4380
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
}
Upvotes: 2