0

I accept the attribute from the JSP page and want to compare. Whether the date passed to the servlet is today, tomorrow, or another day. How can I compare this ???

   Date dateToDo = Date.valueOf(request.getParameter("date")); //for example 2019-08-31

    Date today = new Date (System.currentTimeMillis());
    Date tomorrow = new Date (System.currentTimeMillis() + 86400000);



    if(dateToDo.equals(today)){
        System.out.println("Today!");
    } else if (dateToDo.equals(tomorrow)){
        System.out.println("Tomorrow!");
    } else {
        System.out.println("OTHER DAY");
    }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Ilya Y
  • 744
  • 6
  • 24
  • 1
    Did you check on this [SO question](https://stackoverflow.com/questions/494180/java-how-do-i-check-if-a-date-is-within-a-certain-range)? If you are using Java 8 and above you can check on the [java.time package](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html). – Stefan Freitag Aug 31 '19 at 18:00
  • 1
    Use Java 8 Date Api, It has isAfter() and isBefore() methods, This will help you decide today and tomorrow. – Sunil Aug 31 '19 at 18:07

1 Answers1

3

java.time

    LocalDate dateToDo = LocalDate.parse(request.getParameter("date")); //for example 2019-08-31

    LocalDate today = LocalDate.now(ZoneId.of("Europe/Minsk"));
    LocalDate tomorrow = today.plusDays(1);

    if(dateToDo.equals(today)){
        System.out.println("Today!");
    } else if (dateToDo.equals(tomorrow)){
        System.out.println("Tomorrow!");
    } else {
        System.out.println("OTHER DAY");
    }

Don’t use java.sql.Date. First, it is poorly designed, an awful hack, indeed, and long outdated. Second, it was never meant for anything else than transferring dates to and from SQL databases. Third, while it pretends to be just a date without time of day, it isn’t, but internally stores milliseconds precision, which causes its equals method not to work as expected. Instead I am using LocalDate from java.time, the modern Java date and time API. A LocalDate is what you need: a date without time of day and without time zone.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161