[java] 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();

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?

This question is related to java compare date

The answer is


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(); 
}

Here's what you can do for say yyyy-mm-dd comparison:

GregorianCalendar gc= new GregorianCalendar();
gc.setTimeInMillis(System.currentTimeMillis());
gc.roll(GregorianCalendar.DAY_OF_MONTH, true);

Date d1 = new Date();
Date d2 = gc.getTime();

SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");

if(sf.format(d2).hashCode() < sf.format(d1).hashCode())
{
    System.out.println("date 2 is less than date 1");
}
else
{
    System.out.println("date 2 is equal or greater than date 1");
}

it is esy using time.compareTo(currentTime) < 0

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask {
    static Timer singleTask = new Timer();

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {
        // set download schedule time
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 54);
        calendar.set(Calendar.SECOND, 0);
        Date time = (Date) calendar.getTime();
        // get current time
        Date currentTime = new Date();
        // if current time> time schedule set for next day
        if (time.compareTo(currentTime) < 0) {

            time.setDate(time.getDate() + 1);
        } else {
            // do nothing
        }
        singleTask.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer task is runing");
            }
        }, time);

    }

}

The following will return true if two Calendar variables have the same day of the year.

  public boolean isSameDay(Calendar c1, Calendar c2){
    final int DAY=1000*60*60*24;
    return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
  } // end isSameDay

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.


It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.


This is a very old post though sharing my work. Here is a little trick to do so

DateTime dtStart = new DateTime(Dateforcomparision); 
DateTime dtNow = new DateTime(); //current date

if(dtStart.getMillis() <= dtNow.getMillis())
{
   //to do
}

use comparator as per your requirement


public long compareDates(Date exp, Date today){

        long b = (exp.getTime()-86400000)/86400000;
        long c = (today.getTime()-86400000)/86400000;
        return b-c;
    }

This works for GregorianDates. 86400000 are the amount of milliseconds in a day, this will return the number of days between the two dates.


Here is an another answer: You need to format the tow dates to fit the same fromat to be able to compare them as string.

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

    SimpleDateFormat dateFormatter = new SimpleDateFormat ("yyyy/MM/dd");

    String questionDateStr = dateFormatter.format(questionDate);
    String todayStr = dateFormatter.format(today);

    if(questionDateStr.equals(todayStr)) {
        System.out.println("Both are equals");
    }

java.time

In Java 8 there is no need to use Joda-Time as it comes with a similar new API in the java.time package. Use the LocalDate class.

LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate today = LocalDate.now();

Boolean isToday = date.isEqual( today );

You can ask for the span of time between the dates with Period class.

Period difference = Period.between(date, today);

LocalDate is comparable using equals and compareTo as it holds no information about Time and Timezone.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


It works best....

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

cal1.setTime(date1);
cal2.setTime(date2);

boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

public static double periodOfTimeInMillis(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime());
}

public static double periodOfTimeInSec(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / 1000;
}

public static double periodOfTimeInMin(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 1000);
}

public static double periodOfTimeInHours(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}

public static double periodOfTimeInDays(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}

in my case, I just had to do something like this :

date1.toString().equals(date2.toString())

And it worked!


The easiest way to compare two dates is converting them to numeric value (like unix timestamp).

You can use Date.getTime() method that return the unix time.

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?