Here the regular expression for time validation...



^(([0-9]|([0-1]{0,1}[0-2])):[0-5][0-9]\\s{0,1}(AM|PM|am|pm|aM|Am|pM|Pm))|(((1[0-9])|(2[0-3])):[0-5][0-9])$

Please note that \\s refers to a space character and it's mandatory to use escaping the \ (\\) in Java. If you're going to use this in another language, please remove extra slash.

Below program demonstrates this regular expression usage in Java.


/**
* A demo class to validate the time
* @author Santhosh Reddy Mandadi
* @since 25-Jun-2012
* @version 1.0
*/
public class TimeRegex
{
public static void main(String args[])
{
String times[] = {"01:00 pm", "1:70 am", "23:00am","15:00 am","12","1:00pm","15:00","16:35","9:12am","10:34pm"};
for(String str:times)
{
System.out.println(str+": "+validateTime(str));
}
}
public static boolean validateTime(String time)
{
String pattern = "^(([0-9]|([0-1]{0,1}[0-2])):[0-5][0-9]\\s{0,1}(AM|PM|am|pm|aM|Am|pM|Pm))|(((1[0-9])|(2[0-3])):[0-5][0-9])$";
return time.matches(pattern);
}
}
Output of the above program as follows

01:00 pm: true
1:70 am: false
23:00am: false
15:00 am: false
12: false
1:00pm: true
15:00: true
16:35: true
9:12am: true
10:34pm: true
This has been tested on Java 1.5 and 1.6 versions of Sun Microsystem's Java.