Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates in Java

Tags:

java

date

compare

I need to compare two dates in java. I am using the code like this:

Date questionDate = question.getStartDate(); Date today = new Date();  if(today.equals(questionDate)){     System.out.println("Both are equals"); } 

This is not working. The content of the variables is the following:

  • questionDate contains 2010-06-30 00:31:40.0
  • today contains Wed Jun 30 01:41:25 IST 2010

How can I resolve this?

like image 735
Gnaniyar Zubair Avatar asked Jun 29 '10 20:06

Gnaniyar Zubair


People also ask

How do I compare two dates in a string?

Explanation: Here we are using DateTimeFormatter object to parse the given dates from String type to LocalDate type. Then we are using isEqual(), isAfter() and isBefore() functions to compare the given dates. We can also use the compareTo() function of the LocalDate class to compare the Dates.

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.


2 Answers

Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date() will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:

if (removeTime(questionDate).equals(removeTime(today))    ...  public Date removeTime(Date date) {         Calendar cal = Calendar.getInstance();       cal.setTime(date);       cal.set(Calendar.HOUR_OF_DAY, 0);       cal.set(Calendar.MINUTE, 0);       cal.set(Calendar.SECOND, 0);       cal.set(Calendar.MILLISECOND, 0);       return cal.getTime();  } 
like image 110
Eric Hauser Avatar answered Sep 21 '22 03:09

Eric Hauser


I would use JodaTime for this. Here is an example - lets say you want to find the difference in days between 2 dates.

DateTime startDate = new DateTime(some_date);  DateTime endDate = new DateTime(); //current date Days diff = Days.daysBetween(startDate, endDate); System.out.println(diff.getDays()); 

JodaTime can be downloaded from here.

like image 24
CoolBeans Avatar answered Sep 21 '22 03:09

CoolBeans