4

I'm trying to compare two dates together and I only want to compare the date part not the time part this is how I store date inside my program :

Thu Jan 27 23:20:00 GMT 2011

I have an:

ArrayList<Date> dateList;

and I want to use

dateList.compares(newDate);
// if the answer was false which means I 
// have new date then add the newdate to my list

but since the time part also is involved I can't get the proper answer. How can I fix my problem?

I don't want use JODA-TIME

Jonas
  • 121,568
  • 97
  • 310
  • 388
Vahid Hashemi
  • 5,182
  • 10
  • 58
  • 88

4 Answers4

3

You can compare value by value like 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 Date class, consider using Calendar class instead Here's the most elegant solution, using Calendar and Comparator for 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);
    }
}

Usage:

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);
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
2

Why dont you use compareTo()?

int java.util.Date#compareTo(Date anotherDate)
d-live
  • 7,926
  • 3
  • 22
  • 16
0
Date check_in = new Date(2010,7,31);
Date check_out = new Date(2011,5,22);

int result = check_out.compareTo(check_in); 

if(result<0)
{
  // check_out < check_in
}
else if(result>0)
{
 // check_out > check_in
}
else
{
// check_out == check_in
}       
KK_07k11A0585
  • 2,381
  • 3
  • 26
  • 33
0

You can use this

int compareDates(Calendar c1, Calendar c2) {
    if(c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)){
        return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
    } else if(c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)){
        return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
    }
    return (c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH));
}

EDIT:

Joda time or no this SO post has all answers for date comparison

How to compare two Dates without the time portion?

Community
  • 1
  • 1
mprabhat
  • 20,107
  • 7
  • 46
  • 63