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"); }
Advertisement
Answer
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.