Search code examples
javastringdatedatetimejava-7

Regular expression to match date format MM/dd/yyyy and (or) M/d/yyyy


I need to find a regex that will match both date formats:

MM/dd/yyyy and M/d/yyyy
ex. 01/31/2022, 1/1/2022, 12/13/2022, 12/1/2022

So far I tried

^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9]{1}$)/[0-9]{4}$

Which seems to be the closes to what I need, but it's still not perfect. I am on Java 7 and I need to validate user's input, thus I need to verify if they gave me correct date format. For example, if they enter 13/1/2022, then SimpleDateFormat translates this to Sun Jan 01 00:00:00 CET 2023.


Solution

  • I am on Java 7 and I need to validate user's input thus I need to verify if they gave me correct date format.

    For Java 8+, I recommend this answer by Alexander Ivanchenko. With Java 6 or 7, you can still use that answer with the help of ThreeTen Backport library which backports java.time API to Java 6 and 7.

    However, if you do not want to use the ThreeTen-Backport library and want to stick to Java standard library, you can use DateFormat#setLenient(boolean) with false as the value.

    Demo:

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    public class Main {
        public static void main(String[] args) {
            SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy");
            sdf.setLenient(false);
            String[] arr = { "01/31/2022", "1/1/2022", "12/13/2022", "12/1/2022", "13/01/2022" };
    
            for (String s : arr) {
                try {
                    System.out.println("==================");
                    sdf.parse(s);
                    System.out.println(s + " is a valid date");
                } catch (ParseException e) {
                    System.out.println(e.getMessage());
    
                    // Recommended so that the caller can handle the exception appropriately
                    // throw new IllegalArgumentException("Invalid date");
                }
            }
        }
    }
    

    Output:

    ==================
    01/31/2022 is a valid date
    ==================
    1/1/2022 is a valid date
    ==================
    12/13/2022 is a valid date
    ==================
    12/1/2022 is a valid date
    ==================
    Unparseable date: "13/01/2022"