Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date before method returns false if both dates are equal

Tags:

java

date

when comparing two dates with date before method, if the dates are similar it returns false as follows:

  • date1: Tue Dec 18 00:00:00 GMT+02:00 2012
  • date2: Tue Dec 18 00:00:00 GMT+02:00 2012

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) ?

like image 909
Mahmoud Saleh Avatar asked Dec 18 '12 15:12

Mahmoud Saleh


People also ask

How to check if 2 dates are equal in Java?

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.

How do you check if a Date lies between two dates?

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.

How to compare multiple dates in Java?

allMatch(date::isBefore); boolean afterLatest = ! beforeEarliest && Stream. of(date1, date2, date3). allMatch(date::isAfter);

How to compare null Date in Java?

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.


1 Answers

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.

like image 84
xlecoustillier Avatar answered Nov 15 '22 14:11

xlecoustillier