Search code examples
javadate-comparison

Use compareTo for year,month and day.. Java


I wanna sort the dates out on the screen but the thing is, when I use compareTo method, I can only use it with one of the Date attributes: Year, month or day.. not all of them. This is a custom class, not java.util.Date class.

I am required to sort it out on the screen using compareTo method.

This is what I have done.

public int compareTo(Date date) {
    if(getYear()-date.getYear()>0 && getMonth()-date.getMonth()>0){

        return 1;
    }
    if(getYear()-date.getYear()<0 && getMonth()-date.getMonth()<0 ){

        return -1;
    }
    return 0;
}

Solution

  • You should only compare the months if the years are equal. Similarly, you should only compare the days if the months are equal.

    public int compareTo(Date date) {
        if(getYear() == date.getYear()) {
            if (getMonth() == date.getMonth()) {
                return getDay() - date.getDay ();
            } else {
                return getMonth() - date.getMonth ();
            }
        } else {
            return getYear() - date.getYear();
        }
    }
    

    Note that if for a given property the values of the two Dates are not equal, you can return the difference of those values instead of checking if it's positive or negative and then returning 1 or -1. compareTo is not required to return 1, 0 or -1. It can return any int value.