26

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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Gnaniyar Zubair
  • 8,114
  • 23
  • 61
  • 72

13 Answers13

43

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(); 
}
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Eric Hauser
  • 5,551
  • 3
  • 26
  • 29
  • You may need to adjust for time zone as well. – Matthew Flynn Jun 29 '10 at 20:24
  • Timezones are yet another reason to use Joda Time =) – Eric Hauser Jun 29 '10 at 20:26
  • Thanks Eric.It is working fine. I have one question on this. Instead of writing method to remove the time, cant we use the Dateformat? please clarify – Gnaniyar Zubair Jun 29 '10 at 20:41
  • Sure, you could use string format and compare the strings and it would work fine. However, I believe it is more "correct" to use the date and calendar objects. For one reason, all strings are interned so you are just wasting memory when creating strings for the dates. – Eric Hauser Jun 29 '10 at 21:34
  • Thanks for your clarification Eric. Can you pls explain how we can achieve this using calender object..? – Gnaniyar Zubair Jul 02 '10 at 05:09
  • How do i check if there is a 3 day difference in two dates, imagine i have 28-11-18 in one string and 1-12-18 in another – Femn Dharamshi Dec 10 '18 at 13:03
13

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.

CoolBeans
  • 20,654
  • 10
  • 86
  • 101
10

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.

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
5

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");
}
akjoshi
  • 15,374
  • 13
  • 103
  • 121
Jamal
  • 69
  • 1
  • 4
  • 1
    True, but that is essentially what `equals()` does already. Also I do not think this answers the original question. Sounds like they were trying to compare the *date* and ignore any time portion. Using `==` will not do that. – Leigh Dec 13 '12 at 05:57
  • You are right. I post another answer [link](http://stackoverflow.com/questions/3144387/compare-two-dates-in-java/13870774#13870774) – Jamal Dec 14 '12 at 00:11
  • No need to post another answer, just [update this one](http://stackoverflow.com/posts/13853528/edit). – Leigh Dec 14 '12 at 00:15
5

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
recke96
  • 170
  • 3
  • 8
  • 1
    Good answer but I suggest always passing the optional time zone to the `now` method. If omitted you are depending implicitly on the JVM’s current default time zone. That default can change *at any moment*, even during execution of your code(!). Better to specify the expected/desired time zone. `LocalDate.now( ZoneId.of( "America/Montreal" ) )` – Basil Bourque Sep 18 '16 at 21:19
3

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

    }

}
harsha.kuruwita
  • 1,315
  • 12
  • 21
1

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
musefan
  • 47,875
  • 21
  • 135
  • 185
user569712
  • 11
  • 1
0

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");
    }
Jamal
  • 69
  • 1
  • 4
  • May want to read the previous suggestions before posting [Krolique already suggested that back in 2010](http://stackoverflow.com/a/4196253/104223) ;-) Personally I prefer [Eric's suggestion](http://stackoverflow.com/a/3144444/104223). Strings and date logic do not mix IMO. – Leigh Dec 14 '12 at 00:25
0
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);
}
Yuriy N.
  • 4,936
  • 2
  • 38
  • 31
0

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

0

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

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

And it worked!

Rafa Ayadi
  • 197
  • 1
  • 17
0

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);
piyush
  • 418
  • 1
  • 4
  • 13
  • FYI: The `Calendar` class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes. – Basil Bourque Apr 19 '17 at 18:50
-1

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");
}
Krolique
  • 682
  • 9
  • 14