-3

I'm having two dates for Java util package. Both of them are showing the same date. When I compare both, it shows as wrong. Here is my code and the log

Date date1=new SimpleDateFormat("dd/MM/yy").parse(lastCall);  
logger.info(date1); -->Mon Sep 18 00:00:00 AST 2017
Date todayDate = new Date(); -->Mon Sep 18 12:36:53 AST 2017
System.out.println("Today date :"+todayDate);

if(date1.after(todayDate)){
     System.out.println("Date1 is after Date2");
}

if(date1.before(todayDate)){
    System.out.println("Date1 is before Date2");
}

if(date1.equals(todayDate)){
    System.out.println("Date1 is equal Date2");
}

It goes into before block and prints

  System.out.println("Date1 is before Date2");
Aliy
  • 197
  • 14
  • 4
    well... I mean, 00:00:00 goes before 12:36:53, right? Or am I just crazy now – Shinra tensei Sep 18 '17 at 09:41
  • 1
    I think question is wrong. It should be "How can I compare two dates only for the days? Not for the datetime. There are couple of ways to do that you can set the hour minute seconds to 0 for both of them and then compare etc. – Gunhan Sep 18 '17 at 09:43
  • @Shinratensei, I just want to check both dates. Time can be ignored. – Aliy Sep 18 '17 at 09:43
  • 1
    @Aliy then you're doing it wrong. If you compare the full dates, it's going to compare everything, even at the minimum possible level. You should look for how to compare only the dates, or how to get the days, months and years. – Shinra tensei Sep 18 '17 at 09:45
  • IMHO the first part of the answer is, get rid of the long outdated classes `Date` and `SimpleDateFormat`. [The modern Java date and time API known as JSR-310 or `java.time`](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) is much nicer to work with *and* offers a `LocalDate` class for dates without time-of-day, complete with `isBefore` and `isAfter` methods. – Ole V.V. Sep 19 '17 at 02:37

1 Answers1

1

Date parts are same but time parts are different. So according to comparison of hours, minutes and seconds you end up with this result.

yılmaz
  • 1,818
  • 13
  • 15
  • How this can be covered? I just want only dates to be validated – Aliy Sep 18 '17 at 09:44
  • @Aliy use calendar and remove the time info (set it to 0) – XtremeBaumer Sep 18 '17 at 09:45
  • Use SimpleDateFormat to transform Date object into dd/MM/yyyy format, keep it as String and compare these Strings with equals method. – yılmaz Sep 18 '17 at 09:46
  • I recommend you don’t use the long outdated `Calendar`, nor `SImpleDateFormat` class for this. See the linked question and its answers for better alternatives. – Ole V.V. Sep 19 '17 at 02:40