-1

I want to compare two dates and based on the solution provided in link How to compare dates in Java?, I used the below code.

SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
    String strDate1 = "21-01-2021";
    String strDate2 = "01-02-2021";
    Date date1 = sdf.parse(strDate1);
    Date date2 = sdf.parse(strDate2);
    if (date1.after(date2)) {
        System.out.println(strDate1 + " is after " + strDate2);
    }

    if (date1.before(date2)) {
        System.out.println(strDate1 + " is before " + strDate2);
    }

    if (date1.equals(date2)) {
        System.out.println("Both are same date");
    }

The output I get is 21-01-2021 is after 01-02-2021 which is wrong. Jan 21 2021 is before Feb 01 2021. Can someone please help me to resolve this. Thank you!!

Kitty Raj
  • 91
  • 1
  • 2
  • 12

3 Answers3

4

You use the wrong format for month. mm represents minutes. It should be dd-MM-yyyy

Also, another way to do the comparison is to use date.compareTo(anotherDate) which returns and negative value if date is before another, 0 if date = another and a positive value if date is after another.

tzortzik
  • 4,993
  • 9
  • 57
  • 88
0

try to use this line as a SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
Elyess Eleuch
  • 141
  • 1
  • 5
0

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy") will do the job.

Amit
  • 633
  • 6
  • 13