Home > Back-end >  Regular expression to match date format MM/dd/yyyy and (or) M/d/yyyy
Regular expression to match date format MM/dd/yyyy and (or) M/d/yyyy

Time:12-01

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 SimpleDateFormat translates this to Sun Jan 01 00:00:00 CET 2023

CodePudding user response:

You can successfully parse all specified dates using the same pattern "M/d/yyyy", where M and d denotes the minimal expected number of digits for the Month and the Day of the month, respectively.

There's no need to use regular expressions.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
System.out.println(LocalDate.parse("01/31/2022", formatter));
System.out.println(LocalDate.parse("1/1/2022", formatter));
System.out.println(LocalDate.parse("12/13/2022", formatter));
System.out.println(LocalDate.parse("12/1/2022", formatter));

Output:

2022-01-31
2022-01-01
2022-12-13
2022-12-01

CodePudding user response:

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"
  • Related