Date regex Java

Date regex Java

Date regular expressions can be used to validate if a string has a valid date format and to extract a valid date from a string.

Simple date regex (DD/MM/YYYY)

Below is a simple regex to validate the string against a date format (D/M/YYYY or M/D/YYYY). This however does not guarantee that the date would be valid. You can also replace \\/ with a separator you need.

Pattern.compile("^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$")

Test it!
/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate if a string is a date
        boolean isMatch = Pattern.compile("^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$")
               .matcher("12/12/2022")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract date from a string
        String[] matches = Pattern.compile("[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}")
                          .matcher("I\'m on vacation from 1/18/2021 till 1/29/2021")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [1/18/2021, 1/29/2021]
    }
}

ISO 8061 date regex (e.g. 2021-11-04T22:32:47.142354-10:00)

The ISO 8061 is an international standard for exchanging and serializing date and time data. For validating the format of ISO 8061 date and time and for extracting it a following regular expression could be used:

Pattern.compile("^(?:\\d{4})-(?:\\d{2})-(?:\\d{2})T(?:\\d{2}):(?:\\d{2}):(?:\\d{2}(?:\\.\\d*)?)(?:(?:-(?:\\d{2}):(?:\\d{2})|Z)?)$")

Test it!
/^(?:\d{4})-(?:\d{2})-(?:\d{2})T(?:\d{2}):(?:\d{2}):(?:\d{2}(?:\.\d*)?)(?:(?:-(?:\d{2}):(?:\d{2})|Z)?)$/

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate if a string is an ISO date
        boolean isMatch = Pattern.compile("^(?:\\d{4})-(?:\\d{2})-(?:\\d{2})T(?:\\d{2}):(?:\\d{2}):(?:\\d{2}(?:\\.\\d*)?)(?:(?:-(?:\\d{2}):(?:\\d{2})|Z)?)$")
               .matcher("2021-11-04T22:32:47.142354-10:00")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract ISO date from a string
        String[] matches = Pattern.compile("(?:\\d{4})-(?:\\d{2})-(?:\\d{2})T(?:\\d{2}):(?:\\d{2}):(?:\\d{2}(?:\\.\\d*)?)(?:(?:-(?:\\d{2}):(?:\\d{2})|Z)?)")
                          .matcher("'2017-05-23T15:02:27Z | WARN | Record not found\n2018-05-23T15:02:28Z | WARN | Project with the id '53' was not found")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [2017-05-23T15:02:27Z, 2018-05-23T15:02:28Z]
    }
}

Test it!

True

False

Enter a text in the input above to see the result

Notes on date string regex validation

While there are some regular expressions that allow more complex date validations, it is usually better to validate dates using special date and time libraries. For example, in Java SimpleDateFormat class can be used for these purposes. In this case, the validation will look like this:

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;

public class Main {
    
    public static boolean isValid(String dateStr) {
        DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(false);
        try {
            sdf.parse(dateStr);
        } catch (ParseException e) {
           return false;
        } 
        return true;
    }

     public static void main(String []args) {
        System.out.println(Main.isValid("10/10/2021")); // prints true
     }
}