0

I need to make sure that the users enters a date in the follow format: mm/dd/yyy

I've tried using a simple method to verify that if the parameter given is not null or empty, to check if it matches the required formatting, then if so, set that as the new date.

public void setDate(String dateIn) {

  if ((dateIn != null) && !(dateIn.equals(""))) {
    if (dateIn.equals("%2d" + "/" + "%2d" + "/" + "%4d")) {
      validDate = dateIn;
    }
  }
}

The problem is in my second if statement, I just need to figure out how to make the method take numbers for the day, month, and year.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • You could use regex: `if(dateIn.matches("\\d{2}/\\d{2}/\\d{4}"))`. Another way would be also to try to parse it as a date, and then catch the exception if the date is not valid. – Lino Apr 02 '19 at 14:12
  • 3
    Just try to parse it as a date. If that doesn't work, it's not a valid date. The regex will allow stuff like `02/31/2019` or `99/99/0001`. Those aren't valid dates – VLAZ Apr 02 '19 at 14:14
  • 1
    Instead of a regex, you should call another function that actually validates that it's a valid date, month, and year. 99/99/2000 would pass your current implementation, which is obviously not a valid date. – DrZoo Apr 02 '19 at 14:14
  • Actually, if you are calling `setDate` anyway, why not use a `java.time` objects to store the date? – VLAZ Apr 02 '19 at 14:18
  • I hesitate to mark this as a duplicate of [How to sanity check a date in Java](https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java) because many of the answers there use the notoriously troublesome `SimpleDateFormat` class, which you should never want to do. There is [a good answer here](https://stackoverflow.com/a/39649815/5772882), though. – Ole V.V. Apr 02 '19 at 15:08

1 Answers1

4

Just try to parse the date. I am using the "new" java.time api introduced in Java 8. This api has been thouroughly tested in the JDK and is the way to go (Generally try to do the least amount of work yourself, with a very high probability you're having a problem that has been encountered before):

try {
    DateTimeFormatter.ofPattern("MM/dd/yyyy").parse(dateIn);
    // valid date
} catch(DateTimeParseException e) {
    // invalid date
}
Lino
  • 19,604
  • 6
  • 47
  • 65