Question

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!

Was it helpful?

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());
}

OTHER TIPS

Would it not be easier to just compare deliveryTime to date.getTime() instead of converting deliveryTime to a Date?

Edit

Since you didn't mention you want to ignore milliseconds, you could do:

(deliveryTime / 1000) == (date.getTime() / 1000) 

That should strip out the milliseconds. Alternatively,

Calendar c = Calendar.getInstance();
c.setTime(deliveryTime);
c.set(Calendar.MILLISECOND, 0);
//Clear out the other fields you don't care to compare
Date deliveryDate = c.getTime()

If you make date and deliverydate into date objects, then you can use

date.compareTo(deliveryDate);

This will return: 0 if the dates are the same, a value greater than 0 if date is more recent than deliveryDate, and a value less than 0 if date is before deliveryDate.

To get your dates into date format, you can use something like the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(date);
        Date deliveryDate = sdf.parse(deliveryTime);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top