javadate-comparison

How should I properly compare two dates?


Having some trouble implementing this simple task.

Basically I want to compare two dates(some older date vs new date). I want to know if the older date is more than x months old and y days old.

int monthDiff = new Date().getMonth() - detail.getCdLastUpdate().getMonth();
int dayDiff = new Date().getDay() - detail.getCdLastUpdate().getMonth();
System.out.println("\tthe last update date and new date month diff is --> " + monthDiff);
System.out.println("\tthe last update date and new date day diff is --> " + dayDiff);

If older date is 2012-09-21 00:00:00.0, currently, it will return negative numbers. I need to find out if the older date is EXACTLY 6 months and 4 days before new Date(). I'm thinking of using absolute values of both but just can't brain today.

Edit: I know about joda but I cannot use it. I must use Java JDK. Edit 2: I'll try out the methods listed, if all failed I'll use Joda.


Solution

  • JDK dates have before and after methods, returning boolean, to accomplish your task:

    Date now = new Date();
    Calendar compareTo = Calendar.getInstance();
    compareTo.add(Calendar.MONTH, -6);
    compareTo.add(Calendar.DATE, -4);
    if (compareTo.getTime().before(now)) {
       // after
    } else {
       // before or equal 
    }