Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict two digit day and month parsing for SimpleDateFormat

I am trying to validate date inputs, and I only want them to pass if the day and the month are always two digits. So far I've been doing this with SimpleDateFormat:

    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    df.setLenient(false);

    try
    {
        df.parse("10/1/1987");
        df.parse("1/1/1987");
        df.parse("1/10/1987");
        df.parse("1/1/19");
    }

    catch (ParseException e)
    {
        e.printStackTrace();
    }

All of those cases are passing though, and I don't want any of them to pass.

Is there an easy way to fix this, or will I have to tokenize the string on backslashes first with something like:

String[] dateParts = date.split("/");
if (dateParts.length != 3 && dateParts[0].length() != 2 && dateParts[1].length() != 2 && dateParts[2].length() != 4)
    System.out.println("Invalid date format");
like image 770
Jimmy P Avatar asked Dec 22 '25 23:12

Jimmy P


1 Answers

Use the new java.time instead:

public static void main(String[] args) {
    test("10/10/1987");
    test("10/1/1987");
    test("1/1/1987");
    test("1/10/1987");
    test("1/1/19");
}
private static void test(String date) {
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/uuuu");
    try {
        System.out.println(LocalDate.parse(date, fmt));
    } catch (Exception e) {
        System.out.println(e);
    }
}

Output

1987-10-10
java.time.format.DateTimeParseException: Text '10/1/1987' could not be parsed at index 3
java.time.format.DateTimeParseException: Text '1/1/1987' could not be parsed at index 0
java.time.format.DateTimeParseException: Text '1/10/1987' could not be parsed at index 0
java.time.format.DateTimeParseException: Text '1/1/19' could not be parsed at index 0
like image 108
Andreas Avatar answered Dec 24 '25 13:12

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!