Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates along with time in java

Tags:

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

like image 780
user2636874 Avatar asked Feb 26 '14 11:02

user2636874


People also ask

How can I compare two date and time 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 compare hours in Java?

In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects.

How do you compare years in Java?

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.


1 Answers

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.

like image 74
fge Avatar answered Oct 02 '22 13:10

fge