Home > Enterprise >  SimpleDateFormat is accepting date format which is not mentioned
SimpleDateFormat is accepting date format which is not mentioned

Time:03-24

String dateString = "2022-02-1";
boolean status = false;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
    dateFormat.parse(dateString);
    status = true;
} catch (Exception e) {
    status = false;
}
System.out.println(status);

Here yyyy-MM-dd is the given format so I'm assuming it accepts only '2022-02-01' but it's accepting '2022-02-1' also. How can I make it accept only '2022-02-01' and return false for '2022-02-1'?

CodePudding user response:

Refer to javadoc for class java.text.SimpleDateFormat

For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

In other words, SimpleDateFormat treats dd the same as d when parsing a string.

Since Java 8, you should be using date-time API.

String dateString = "2022-02-1";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(formatter.parse(dateString));

Running above code throws an exception.

Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-02-1' could not be parsed at index 8
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)

CodePudding user response:

The Answer by Abra is correct. But to more directly address a solution, trap for DateTimeParseException to detect faulty input.

No need to specify a formatting pattern in your case. Your expected input format complies with ISO 8601 standard. Those standard formats are used by default in java.time when parsing/generating text.

try {
    LocalDate ld = LocalDate.parse( input ) ;
    … handle valid input
} catch ( DateTimeParseException e ) {
    … handle faulty input
}
  • Related