Search code examples
javaandroiddatedatetimeandroid-date

Dates are not getting compared?


I am comparing dates in my android application, how ever for my equal dates, compareTo or equals method returns me that dates are not equal. I have debugged through and I can see both my objects have same values. But some how it is not working. Following is the way I am doing it:

public static boolean compareDates(long deliveryTime, Date date) throws ParseException {

    Date deliveryDate = convertLongToDate(deliveryTime);
    deliveryDate.setHours(0);
    deliveryDate.setMinutes(0);
    deliveryDate.setSeconds(0);

    if (deliveryDate.equals(date))
    {
        return true;
    }

    return false;
}

My date object does not contain time, so I am setting deliverTime's time to 0(zero) as well, so that both objects can have same values. but it does not work. Any help is appreciated. Thanks!


Solution

  • I would create a Date object out of the deliveryTime, and then compare the hours, minutes and seconds. A code is below.

    public static boolean compareDates(long deliveryTime, Date date) {
      Date d = new Date(deliveryTime);
      return(d.getHours() == date.getHours() && d.getMinutes() == date.getMinutes() && d.getSeconds() == date.getSeconds());
    }