0

I'm programming a window where the user has to type a date on a input field but I don't know how to check if the day or month are coherent or not (like day between 1-31 and month between 1-12)

    String string = "26/03/2017";
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy") ;

    try {
        Date date = format.parse(string);
    } catch (ParseException e) {
        e.printStackTrace();
    }

This is the piece of code where I'm formatting the Date, but I have no idea to check what I said before.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
gab
  • 29
  • 5

4 Answers4

0

Trying to parse a string like this: string = "36/03/2017"; can return a totally legal date object but an incorrect value respect the string. for that case you can use the lenient flag of the class SimpleDateFormat, setting that flag to false will throw an exception for invalid strings representations of a date (e.g. 29 Feb 2017)

now, you can set the flag Lenient to false, and catch the exception

String string = "36/03/2017";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
try {
    Date date = format.parse(string);
    System.out.println(date);
} catch (ParseException e) {
     e.printStackTrace();
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

DateFormat has a property which named 'lenient' is default true. You must set format.setLenient(false) to check validity of the date. if incorrect date is parsed, you get a ParseException.

0

2017 answer.

    DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/uuuu")
                                .withResolverStyle(ResolverStyle.STRICT);
    try {
        LocalDate.parse(string, format);
    } catch (DateTimeParseException e) {
        System.out.println("Not a valid date: " + string);
    }

While SimpleDateFormat has two degrees of strictness, lenient and non-lenient, DateTimeFormatter has three, strict, smart and lenient. For validation I recommend strict. Smart is the default, so we need to set it explicitly.

There are many more details in this answer.

Community
  • 1
  • 1
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
-1

I suggest to use regex. For your date format it should be something like:

(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d

You can also find more patterns and validate them here: http://html5pattern.com/Dates

Planck Constant
  • 1,406
  • 1
  • 17
  • 19