Wednesday, September 19, 2012

JAVA: use regex to validate date and time.

I tried to search correct regex for date and time on google and found that many of them are not working.

Finally, I found the correct one and the java methods shows below.
 /**  
  * Check that a date is formatted according to the following convention:  
  * DD/MM/YYYY OR DD.MM.YYYY OR DD-MM-YYYY  
  * @param dateStr a date string.  
  * @return true if the date text should be rejected  
  */  
  private boolean invalidDate(String dateStr) {  
  String regex = "^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$";  
  return !Pattern.matches(regex, dateStr);  
  }  
  /**  
  * Check that a time is formatted according to the following convention:  
  * HH:MM:SS AM/PM  
  * @param timeStr a time string.  
  * @return true if the time text should be rejected  
  */  
  private boolean invalidTime(String timeStr) {  
  String regex = "^(([0]?[1-9])|([1][0-2])):(([0-5][0-9])|([1-9])):([0-5][0-9]) [AP][M]$";  
  return !Pattern.matches(regex, timeStr);  
  }  

2 comments:

  1. It is better to use DateFormat to parse and validate the date string rather than use regex to validate it. Since regex is not easy to read and maintain and your method cannot even detect some invalid case such as "31/02/2000" which does not exist.

    ReplyDelete
    Replies
    1. u r right.
      regex is quite useful too, especiall when you are working in both java and js.

      I just want to post the right regex for date and time here.

      Delete