when comparing two dates with date before method, if the dates are similar it returns false as follows:
the method date1.before(date2)
always return false in thise case, which does not make sense to me (doesn't apply to my case in other words). i want to check if a date (day/month/year) equals today's date (day/month/year) ?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
To check if a date is between two dates: Use the Date() constructor to convert the dates to Date objects. Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.
allMatch(date::isBefore); boolean afterLatest = ! beforeEarliest && Stream. of(date1, date2, date3). allMatch(date::isAfter);
The equals() method compares two Dates for equality and returns true if and only if the argument is not null and is a Date object that represents the same point in time as the invoking object, else it will return false . In other words, it checks if the references point to the same object in memory.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With