Gnaniyar Zubair Gnaniyar Zubair - 1 year ago 136
Java Question

Compare two dates in Java

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

Date questionDate = question.getStartDate();
Date today = new Date();

System.out.println("Both are equals");

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

  • questionDate
    2010-06-30 00:31:40.0

  • today
    Wed Jun 30 01:41:25 IST 2010

How can I resolve this?

Answer Source

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.set(Calendar.HOUR_OF_DAY, 0);  
    cal.set(Calendar.MINUTE, 0);  
    cal.set(Calendar.SECOND, 0);  
    cal.set(Calendar.MILLISECOND, 0);  
    return cal.getTime(); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download