tags:

views:

1859

answers:

7

How can I check if date is between two dates in java (Not through a MySQL query)?

+8  A: 

Like so:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.compareTo(min) >= 0 && d.compareTo(max) <= 0;

You can use > instead of >= and < instead of <= to exclude the endpoints from the sense of "between."

Jason Cohen
Thanks for your immediate Response.
Gnaniyar Zubair
This doesn't always work. I have had problems using compareTo on Date objects. Jan 1 2006 was apparently after Apr 1 2006 in one of my programs.
KitsuneYMG
+27  A: 

This might be a bit more readable:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.after(min) && d.before(max);
Nathan Feger
A very healthy 9 seconds faster, sir.
Tetsujin no Oni
between can include the endpoints, in which case you could use return !d.before(min)
Patrick McDonald
@Tetsujin no Oni sorry man, its a good thing I don't have a big deliverable due in a couple weeks that is both helped and hurt by SO. :)
Nathan Feger
oh wait I do...
Nathan Feger
+1  A: 

you can use getTime() and compare the returned long UTC values.

EDIT if you are sure you'll not have to deal with dates before 1970, not sure how it will behave in that case.

+1  A: 

Another option

min.getTime() <= d.getTime() && d.getTime() <= max.getTime()
David
+3  A: 

You might want to take a look at Joda Time which is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.

willcodejavaforfood
Yes my immediate thought was to suggest Joda time but I can't see anything in the API to support a "within range" test. Anyone else?
Dave Tapley
I am not suggesting Joda for this particular problem, since it already has numerous solutions.
willcodejavaforfood
But you would create an Interval in Joda Time to do this
willcodejavaforfood
A: 

If you don't know the order of the min/max values

Date a, b;   // assume these are set to something
Date d;      // the date in question

return a.compareTo(d) * d.compareTo(b) > 0;
Peter Lawrey
A: 

import java.util.Date;

public class IsDateBetween {

public static void main (String[] args) {

      IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date

} public IsDateBetween(String dd) {

       long  from=Date.parse("01/01/2000");  // From some date

       long to=Date.parse("12/12/2010");     // To Some Date

       long check=Date.parse(dd);

       int x=0;

      if((check-from)>0 && (to-check)>0)
      {
             x=1;
      }

 System.out.println ("From Date is greater Than  ToDate : "+x);
}   

}

Biswabrata Banerjee