You can compare value by value similar to this
d1.getDate().equals(d2.getDate()) && d1.getYear().equals(d2.getYear()) && d1.getMonth().equals(d2.getMonth())
or
Date date1 = new Date(d1.getYear(), d1.getMonth(), d1.getDate()); Date date2 = new Date(d2.getYear(), d2.getMonth(), d2.getDate()); date1.compareTo(date2);
If you work with the Date class, use the Calendar class instead. Here is the most elegant solution using Calendar and Comparator to do this
public class CalendarDateWithoutTimeComparator implements Comparator<Calendar> { public int compare(Calendar cal1, Calendar cal2) { if(cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)) { return cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR); } else if (cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)) { return cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH); } return cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH); } }
Using:
Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); // these calendars are equal CalendarDateWithoutTimeComparator comparator = new CalendarDateWithoutTimeComparator(); System.out.println(comparator.compare(c1, c2)); List<Calendar> list = new ArrayList<Calendar>(); list.add(c1); list.add(c2); Collections.sort(list, comparator);
source share