-1

I am working on an old java 7 environment that my work still uses and I need to validate user dates. The issue is that I need return an error if the user inputs an invalid date so I am trying to implement this answer using the java calendar object though right now if the user types the date 2001-02-31 the java date object converts the date to 2001-03-02 thus making the calendar never throw the exception to the user because the converted date is valid. I am wondering how do I get around the date being converted automatically being converted so its never converted?

Here is my code so far:

//formats the date for us
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date checkLDate = dateFormatter.parse(request.getParameter("loDate"));
out.print(checkLDate + "<br/>");


//checking to see if the dates are valid
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(checkLDate);
try {
    cal.getTime();
    //this print is just to debug where the code went
    out.print("hello");
}
catch (Exception e) {
    out.print("Invalid date");
}

Hopefully, that helps and thank you for all the help in advance

LucyEly
  • 63
  • 1
  • 13
  • 1
    On Java 7 consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTen Backport](https://www.threeten.org/threetenbp/) to your project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 14 '19 at 04:41
  • There are 21 answers to the question you linked to. It seems you picked the first one, but that one is incorrect as also stated in the comments under it. IMO [the answer by Basil Bourque](https://stackoverflow.com/a/39649815/5772882) is the best one. It will give you the best and strictest validation. – Ole V.V. Dec 14 '19 at 04:46
  • 1
    The answer you have accepted below was already given three times under the question that you linked to. I have closed this question as a duplicate. – Ole V.V. Dec 14 '19 at 04:54

1 Answers1

1

You have to set lenient to false on SimpleDateFormat object:

dateFormatter.setLenient(false)

in the Calendar it is to late.

Jens
  • 67,715
  • 15
  • 98
  • 113