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
2009-05-19 14:19:53
Thanks for your immediate Response.
Gnaniyar Zubair
2009-05-19 14:23:33
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
2009-05-19 14:28:31
+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
2009-05-19 14:22:19
between can include the endpoints, in which case you could use return !d.before(min)
Patrick McDonald
2009-05-19 14:28:14
@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
2009-05-19 14:35:21
+1
A:
Another option
min.getTime() <= d.getTime() && d.getTime() <= max.getTime()
David
2009-05-19 14:37:34
+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
2009-05-19 14:38:10
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
2009-05-19 14:43:31
I am not suggesting Joda for this particular problem, since it already has numerous solutions.
willcodejavaforfood
2009-05-19 15:12:04
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
2009-05-19 19:28:31
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
2010-08-13 01:40:06