The following class shows how you can comparison two dates without considering their absolute time i.e only considering their days:
import java.util.Date;
import java.util.Calendar;
public class DateComparisonTest {
/**
* Compares the two given date without taking the hour and minute in to account
* So comparing two dates with 1 hour difference will return 0 which means that
* both dates are equal. 1 is returned if <code>date1<code> is after <code>date2<code>
* and -1 if date2 is after date1
*
* @param date1
* @param date2
* @return 1 if date1 is after date2 -1 if date1 is before date2 and 0 if date1 equals date2
* @see java.util.Date#compareTo(java.util.Date)
*/
public static int compare(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
if (year1 == year2) {
if (day1 == day2) {
return 0;
}
else {
if (day1 > day2) {
return 1;
}
else {
return -1;
}
}
}
else if (year1 > year2) {
return 1;
}
else {
return -1;
}
}
public static void main(String[] args) {
Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int d = cal.get(Calendar.DAY_OF_YEAR);
cal.set(Calendar.DAY_OF_YEAR, d - 5);
Date fiveDaysAgo = cal.getTime();
if (compare(today, fiveDaysAgo) > 0) {
System.out.println("today is after 5 days ago! ");
}
if (compare(fiveDaysAgo, today) < 0) {
System.out.println("5 days ago is before today! ");
}
cal.setTime(today);
int hourOfDay= cal.get(Calendar.HOUR_OF_DAY);
cal.set(Calendar.HOUR_OF_DAY,hourOfDay+2);
Date stillToday= cal.getTime();
if (compare(today, stillToday) == 0) {
System.out.println("today is just today! ");
}
}
}