Date before method returns false if both dates are equal

You can simply test the inverse :

!date1.after(date2)

You can always convert a strict order check to a non-strict check in this manner. Since mathematically :

a > b ⇔ ¬ (a ≤ b)

As date1.equals(date2), it is normal that date1.before(date2) returns false. As will do date1.after(date2).

Both dates are the same, so one is not before the other.

From javadoc :

true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when; false otherwise.

Try something like :

if(date1.before(date2) || date1.equals(date2)) ...

Answers provided below suggest testing for the inverse, and they're right:

if(!date1.after(date2)) ...

Both tests are equivalent.


If the dates are equal, then obviously one is NOT before the other: false is the correct return for date1.before(date2) where date1 == date2.

If you need to include equality, why not do a negation on .after() (obviously if date 1 is NOT after date 2, then it is equal or before), but I would make sure that this is actually correct logic for what you are trying to accomplish.

If equality is a special case that needs to be handled differently, then have a separate test for .equals().


you can use the inverse like it was proposed by bowmore: !date1.after(date2)

Or if you are looking for ranges, between can include the endpoints, in which case you could use return !d.before(min) && !d.after(max)

Tags:

Java

Date