This question already has an answer here:
How can I check if a date is between two other dates, in the case where all three dates are represented by instances of java.util.Date
?
This question already has an answer here:
How can I check if a date is between two other dates, in the case where all three dates are represented by instances of java.util.Date
?
Like so:
You can use
>
instead of>=
and<
instead of<=
to exclude the endpoints from the sense of "between."Here's how to find whether today is between 2 months:
and call it like:
Another option
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.
This might be a bit more readable:
Here's a couple ways to do this using the Joda-Time 2.3 library.
One way is to use the simple
isBefore
andisAfter
methods on DateTime instances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.Another way is to build an Interval in Joda-Time. The
contains
method tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically[)
.See both ways in the following code example.
Convert the java.util.Date instances to Joda-Time
DateTime
instances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specificDateTimeZone
object rather than rely on JVM’s default time zone.Compare by testing for before/after…
Using the Interval approach instead of isAfter/isBefore…
Dump to console…
When run…