-2

Possible Duplicate:
Compare dates in java

I am getting two dates from server in yyyy-MM-dd format. I have to compare between these two dates. I used compareTo() method to compare two dates. what is more easier way to compare two dates assuming my server will always return not null value in yyyy-MM-dd format?

Define the method

void compareTwoDates(String startDate, String endDate){
        switch(startDate.compareTo(endDate)){
            case -1:
                //START DATE IS BIGGER THAN END DATE
                System.out.println(endDate+" IS BIGGER THAN "+startDate);
                break;
            case 0:
                //BOTH DATE ARE SAME
                System.out.println("SAME DATE");
                break;
            case 1:
                //END DATE IS BIGGER
                System.out.println(startDate+" IS BIGGER THAN "+endDate);
                break;
        }
    }

call the method using following way

compareTwoDates("2012-05-06", "2012-04-08");
compareTwoDates("2012-04-09", "2012-04-09");
compareTwoDates("2012-04-09", "2011-05-10");
Community
  • 1
  • 1
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243

4 Answers4

2

Use methods Date.before() and Date.after()

mishadoff
  • 10,719
  • 2
  • 33
  • 55
1

Don't compare String as if they were dates... only pain and misery can come from that approach.

Something like:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d1 = sdf.parse("2012-04-04");
    Date d2 = sdf.parse("2012-04-05");

Will suit your needs, then you can use the Date compareTo methods, that WILL compare dates as they're supposed to be compared, not as String values that have no context of years, months, etc.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
1

Check this sample.

       if(date1.after(date2)){
           System.out.println("Date1 is after Date2");
        }
        if(date1.before(date2)){
             System.out.println("Date1 is before Date2");
        }
        if(date1.equals(date2)){
             System.out.println("Date1 is equal Date2");
        }
Sai Ye Yan Naing Aye
  • 6,622
  • 12
  • 47
  • 65
0

use java.util.Calendar class- before and after will do the work.

for parse strings use java.text.SimpleDateFormat

shem
  • 4,686
  • 2
  • 32
  • 43