0

I need to filter a date from the "From date" to the "To date" using the "Current date" filter.

Here is the code I use in my java application:

String from = "19/05/1991";
String cmp = "23/05/1991";
String to = "23/12/2015";

if (from.compareTo(cmp) <= 0 && to.compareTo(cmp) >= 0) {
    System.out.println("Date lies between from and to date");
}

Is this code correct?

Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
  • 1
    Sort of, although that answer and the answer it references assumes you have Dates already. A good answer to this one might include why comparing Strings like that won't work (although if the dates were yyyy/mm/dd it would work fine), and how to get a String into a Date. – blm Oct 03 '15 at 07:39

1 Answers1

0

You should do it like this:

String from = "19/05/1991";
String cmp = "23/05/1991";
String to = "23/12/2015";

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = format.parse(from);
Date date2 = format.parse(cmp);
Date date3 = format.parse(to);

if(date1.before(date2) && date3.after(date2)) {
   System.out.println("Date lies between from and to date");
}

See Date#after and Date#before

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23