2

I have a problem with Date instance. I did the following:

Date startDate = new Date(); //this is from database value
Date todayDate = new Date(); //this is created locally

Now when am trying to compare them, the only issue is that the Date instance will have time, so when I check if they are equal it probably wouldn't give the same thing I expect, but rather less or more. I tested the following:

    System.out.println(rsv.startDate);
    System.out.println("Today date:"+todayDate);
    if(rsv.startDate.equals(todayDate)){
        System.out.println("Equal!");
    }else if(rsv.startDate.after(todayDate)){
        System.out.println("After!!");
    }else{
        System.out.println("Before!!!!");
    }

and although both are 5th feb but it shows output of Before instead of equal. How can I remedy this? I know about SimpleDateFormat but that would change the date to strings.

Thanks,

sys_debug
  • 3,883
  • 17
  • 67
  • 98
  • 2
    Are you trying to figure out if both dates are in the same day? ( http://stackoverflow.com/questions/2517709/java-comparing-two-dates-to-see-if-they-are-in-the-same-day ). What's wrong with SimpleDateFormat then? – Brian Clozel Feb 05 '12 at 10:50

3 Answers3

2

You can strip out the time from the current Date object:

   Date date = new Date();

   Calendar dCal = Calendar.getInstance();
   dCal.setTime(date);
   dCal.set(Calendar.HOUR_OF_DAY, 0);
   dCal.set(Calendar.MINUTE, 0);
   dCal.set(Calendar.SECOND, 0);
   dCal.set(Calendar.MILLISECOND, 0);

   date = dCal.getTime();

And then make your comparision.

Alternatively, if you need in your project more date/time processing power, you can use joda date time library: http://joda-time.sourceforge.net

MidnightDate class is suitable for this specific usecase: http://joda-time.sourceforge.net/api-release/org/joda/time/DateMidnight.html

dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • I've used Joda time in other part of the program but do not intend to use it in this module :) Thanks though for recommendation. will try the above code :) – sys_debug Feb 05 '12 at 10:46
2

For Date operation you can use Joda utility. Following snippet code shows compare two date :

DateTime one = new DateTime(original-Date-1);
DateTime two = new DateTime(original-Date-2);

LocalDate oneDate = one.toLocalDate();
LocalDate twoDate = two.toLocalDate();

return oneDate.compareTo(twoDate);

You can see: http://joda-time.sourceforge.net/index.html

Sam
  • 6,770
  • 7
  • 50
  • 91
0

Date contains both the date and time. Equals() will only return true if the time is also the same. To make the comparison work, you need to make sure that the time portion of both Date objects is the same (eg all set to zero).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197