Search code examples
javadate-comparison

Date compare without time


I realise this is a question asked many times, but I have sifted through and can't seem to find an answer that would assist me completely. I'd start with saying that I can't use Joda.

I am making a change to a program that requires me to compare a user input date (From Date) with a date from a column.

The request can't be done using SQL as the filter for the date check on this column has to be ran after the results are returned.

The code is checking an entry on the table, making a comparison between the "From Date" and the field entry, and then it will display that row of data dependent on whether the boolean returns a true or false.

All the code is working fine apart from one section. It checks if the date on the table is more than or equal to the "From Date".

Example:

The user enters the date 13/04/2015.

The program SHOULD return all rows with the date field that is 13/04/2015 or later.

The program actually returns all dates that are 1 day after this date. i.e. anything that is 14/04/2015 and onwards.

My code for the check on this section is:

private boolean checkArngdDateCriteria(OrderBean singleOrderBean) {
    if (getSearchArngdFromDate().getValue()!= null || getSearchArngdToDate().getValue()!= null) {
        Date checkArngdToDate = (Date)getSearchArngdToDate().getValue();
        Date checkArngdFromDate = (Date)getSearchArngdFromDate().getValue();

        if (getSearchArngdFromDate().getValue()!= null && getSearchArngdToDate().getValue()== null && singleOrderBean.getOrdStatD()!= null) {
            if (singleOrderBean.getOrdStatD().after(checkArngdFromDate) || singleOrderBean.getOrdStatD().equals(checkArngdFromDate)) {
                return true;
            }
        }

EDIT:

//This retrieves the date from the results table
singleOrderBean.getOrdStatD()

//This retrieves the value from the user input field (retrieved as Object)
getSearchArngdFromDate().getValue()

Does anybody know a bit of code that would make it so the From Date would be treated as equal or less than the table date if they were both 13/04/2015?


Solution

  • The Date class includes time fields (and various other fields). You are comparing for 'after' or 'equals'. However, 'equals' is not doing what you think it's doing. It's not just comparing dates. It will only return true if all fields are equal. The easiest way to fix it is, instead of doing 'after or equals', do 'not before'.

            if (!singleOrderBean.getOrdStatD().before(checkArngdFromDate)) {
                return true;
            }