How to compare two dates along with time in java
Solution 1:
Since Date
implements Comparable<Date>
, it is as easy as:
date1.compareTo(date2);
As the Comparable
contract stipulates, it will return a negative integer/zero/positive integer if date1
is considered less than/the same as/greater than date2
respectively (ie, before/same/after in this case).
Note that Date
has also .after()
and .before()
methods which will return booleans instead.
Solution 2:
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Solution 3:
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)