-1

Hi is there a way to check if an input is a date in Java, the date format is DD/MM/YYYY so int\int\int I have the basic check if (x != "") but I was wondering if you check that it is a date.

Now I'me getting a new error code:

try {
      date = (Date) dateFormat.parse(dateInput);
} catch (ParseException e1) {
                System.out.println("FAIL!!!!!!!!");
                JOptionPane.showMessageDialog(null, "Date entered is incorrect, please close this window and try again");
                new BookApp();
            }

The indents probably got messed in when I copied and pasted it, but when the format is wrong it works and the dialog menu pops up. But when I give 12\08\2015 it give a ClassCastError. How do I get this working?

Neo Streets
  • 525
  • 1
  • 7
  • 15

2 Answers2

3

1) Create a formatter for your date pattern :

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

2) Try to format your String input to a date :

Date date = dateFormat.parse(input);

Now, if the input doesn't match your pattern, you get a ParseException.

Arnaud
  • 17,229
  • 3
  • 31
  • 44
0

You can always try to parse the date and capture if the parse was successful or not.

The SimpleDateFormat will throw an exception if the string was not parsable as a date.

public boolean isDate(String dateString) {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        return dateFormat.parse(dateString) != null;
    } catch (ParseException e) {
        return false;
    }
}
pfranza
  • 3,292
  • 2
  • 21
  • 34