I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String matchDateTime = sdf.parse("2014-01-16T10:25:00"); Date matchDateTime = null; try { matchDateTime = sdf.parse(newMatchDateTimeString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // get the current date Date currenthDateTime = null; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date dt = new Date(); String currentDateTimeString = dateFormat.format(dt); Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString); try { currenthDateTime = sdf.parse(currentDateTimeString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Now I want to compare the above two dates along with time. How should I compare in Java.
Thanks
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.
In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects.
The compareTo() method of Year class in Java is used to compare this Year object with another Year object. The comparison of Year object is based on the values of Year. Parameter: This method accepts a single parameter otherYear.
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.
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