Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - Date before method returns false if both dates are equal

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

question from:https://stackoverflow.com/questions/13936576/date-before-method-returns-false-if-both-dates-are-equal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...