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
  • 67,715
  • 15
  • 98
  • 113
niks
  • 1,063
  • 2
  • 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.

nano_nano
  • 12,351
  • 8
  • 55
  • 83
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
  • 36,381
  • 8
  • 49
  • 73