What is Java reg ex to check for date and time?

JavaServer Side ProgrammingProgramming

To match a regular expression with the given string You need to:.

  • Compile the regular expression of the compile() method of the Pattern class.
  • Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
  • The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data.

Example

Following is a Java regular expression example matches only date

Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sample {
   public static void main(String args[]){  
    //Creating the list to store dates
      List dates = new ArrayList();
      dates.add("25-12-1990");
      dates.add("25/12/1990");
      dates.add("2010-06-24 06:30");
      dates.add("05-02-1990");
      dates.add("1920-11-03 12:40");      
      //Regular expression to match dates
      String regex = "[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);      
      //Matching each date
      for(Object date : dates) {        
          Matcher matcher = pattern.matcher((CharSequence) date);
          System.out.println(date +": "+ matcher.matches());
       }      
   }
}

Output

25-12-1990: false
25/12/1990: false
2010-06-24: true
05-02-1990: false
1920-11-03: true

Example

Following example matches the date and time −

Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sample {
   public static void main(String args[]){  
    //Creating the list to store dates
      List dates = new ArrayList();
      dates.add("25-12-1990");
      dates.add("25/12/1990");
      dates.add("2010-06-24 12:30:40");
      dates.add("05-02-1990 44:205:40");
      dates.add("1920-11-03 06:25:40");      
      //Regular expression to match dates
      String regex = "[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);      
      //Matching each date
      for(Object date : dates) {        
          Matcher matcher = pattern.matcher((CharSequence) date);
          System.out.println(date +": "+ matcher.matches());
       }      
   }
}

Output

25-12-1990: false
25/12/1990: false
2010-06-24 12:30:40: true
05-02-1990 44:205:40: false
1920-11-03 06:25:40: true
raja
Published on 06-Feb-2021 04:32:12
Advertisements