javadatecalendarcomparison

How can I compare two Calendar dates?


I have a Java problem where I need to check if an item has expired. This is supposed to check if the item is at least x (x is an integer and can be set to any integer value) months old.

Just to reclarify Supposing I have a pack of eggs, I want to check if it has been 1 months since I added them (dateAdded).

I wrote a simple comparison but it doesn't seem to give the correct response. Here is the code.

public Boolean isEndOfLine() {
    Calendar today = Calendar.getInstance();
    if(today.compareTo(dateAdded) >= END_OF_LINE) {
        return true;
    } else {
        return false;
    }
}

The value of end of line is an integer 12 i.e 12 months.


Solution

  • I do not hold javadoc in my head, but along the lines of:

    dateAdded.add(Calendar.Month, END_OF_LINE).compareTo(today) > 0