0

I want to compare two date values in Java

Date date1=10-Oct-2014 00:00:00(value fetched from DB)
Date date2=10-Oct-2014 00:00:00(value fetched from DB)

How do I convert this date values into String format in Java so that I cant compare them or else is there any way I can compare these dates.

Jens
  • 63,364
  • 15
  • 92
  • 104
niks
  • 1,023
  • 1
  • 9
  • 18

2 Answers2

2

I would compare the long values of both dates like this: if the dates are nullable dont forgett the nullcheck!

if (date1!=null && date2 != null){
   if (date1.getTime() == date2.getTime()){
      System.out.println("Dates are equal");
   }
}

There is no need to cast the Date objects to String objects.

s_bei
  • 11,949
  • 8
  • 50
  • 73
0

You should be using compareTo method for less than or equal or greater than. You could do it like:

 int dateComparison = date1.compareTo(date2);
 if (dateComparison  == 0) {
     //both dates are equal
 } else if (dateComparison  < 0) {
     //date2 is greater
 } else {
     //date1 is greater
 }

if you are just looking for equality, you could use equals method on date like below:

 if (date1.equals(date2)) {
    //two dates are equal
 }
SMA
  • 35,277
  • 7
  • 46
  • 71