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 the 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)) ...
The answers provided below suggest testing for the inverse, and they're right:
if (!date1.after(date2)) ...
Both tests are equivalent.
Answer from xlecoustillier on Stack OverflowVideos
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 the 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)) ...
The answers provided below suggest testing for the inverse, and they're right:
if (!date1.after(date2)) ...
Both tests are equivalent.
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)
Another more compact way of organizing the conditionals:
if (yearCurr != year) {
return year < yearCurr;
}
if (monthCurr != month) {
return month < monthCurr;
}
return day <= dayCurr;
Just wanted to chime in:
- Nobody mentioned this, but
isValidDate()to determine whether 1 date is earlier than another date is frankly terrible. Call itisEarlierDate() - Where are the variables? Are those variables all defined outside of this function. That does not look good.
If there is one thing you learn today it is that this
if(day<=dayCurr) return true; else return false;should always be written as
return day<=dayCurr- As per @Heslacher, write out your variable names
This is my over-commented counter-proposal:
function isEarlierDate(){
return year < currentYear || //Last year is in the past
year == currentYear && month < currentMonth || //This year, earlier month is in the past
year == currentYear && month == currentMonth && day < currentDay || //..
false; //This is clearly not an earlier date
}