0
 public static void main(String [] args){
    String date = "01/08/2017";

    Date todaydate = new Date();

    SimpleDateFormat myFormat = new SimpleDateFormat("dd/mm/yyyy");
    try {
        Date expiry = myFormat.parse(date);

        if(expiry.compareTo(todaydate) >0){
            System.out.println("false");
        }

        else{
            System.out.println("true");
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

I am comparing date 01/08/2017 to current date. It should return false. However, it is returning true, even if I use isAfter in the if condition.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Muzogeek
  • 53
  • 7
  • 3
    Your date format is wrong. Use `dd/MM/yyyy` instead of `dd/mm/yyyy`. Lower-case `mm` means **minutes**, not months. See the [API docs](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) of `SimpleDateFormat`. – Jesper Jan 17 '17 at 12:09

3 Answers3

3

This should do the trick

SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
Rauno
  • 616
  • 8
  • 22
1

The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

you need to change the condition

 if(expiry.compareTo(todaydate) <0)

Go to this link n see the methods of the dates https://www.tutorialspoint.com/java/util/date_compareto.htm

Sanket Patel
  • 901
  • 9
  • 21
1

besides the format, compareTo() is returning true, always that the date is after the argument, which is right. If the dates where equals it would return 0.

Check the docs: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo%28java.util.Date%29

Iván Rodríguez Torres
  • 4,293
  • 3
  • 31
  • 47