Time in 12-Hour Format Regular Expression Pattern


(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)

Description


(				#start of group #1
 1[012]				#  start with 10, 11, 12
 |				#  or
 [1-9]				#  start with 1,2,...9
)				#end of group #1
 :				#    follow by a semi colon (:)
  [0-5][0-9]			#      follw by 0..5 and 0..9, which means 00 to 59
            (\\s)?		#        follow by a white space (optional)
                  (?i)		#          next checking is case insensitive
                      (am|pm)	#            follow by am or pm

The 12-hour clock format is start from 0-12, then a semi colon (:) and follow by 00-59 , and end with am or pm.

Java Regular Expression Example


package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Time12HoursValidator{
	
	  private Pattern pattern;
	  private Matcher matcher;
 
	  private static final String TIME12HOURS_PATTERN = 
                                "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)";
	  
	  public Time12HoursValidator(){
		  pattern = Pattern.compile(TIME12HOURS_PATTERN);
	  }
	  
	  /**
	   * Validate time in 12 hours format with regular expression
	   * @param time time address for validation
	   * @return true valid time fromat, false invalid time format
	   */
	  public boolean validate(final String time){		  
		  matcher = pattern.matcher(time);
		  return matcher.matches();	    	    
	  }
}

Time format that match:

1. “1:00am”, “1:00 am”,”1:00 AM” ,
2. “1:00pm”, “1:00 pm”, “1:00 PM”,
3. “12:50 pm”

Time format doesn’t match:

1. “0:00 am” – hour is out of range [1-12]
2. “10:00 am” – only one white space is allow
3. “1:00” – must end with am or pm
4. “23:00 am” -24-hour format is not allow
5. “1:61 pm” – minute is out of range [0-59]
6. “13:00 pm” – hour is out of range [1-12]
7. “001:50 pm” – invalid hour format
8. “10:99 am” – minute is out of range [0-59]
9. “01:00 pm” – 24-hour format is not allow
10. “1:00 bm” – must end with am or pm

Unit Test – Time12HoursValidatorTest


package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Time 12 hours format validator Testing
 * @author mkyong
 *
 */
public class Time12HoursValidatorTest {
 
	private Time12HoursValidator time12HoursValidator;
    
	@BeforeClass
        public void initData(){
		time12HoursValidator = new Time12HoursValidator();
        }
	
	@DataProvider
	public Object[][] ValidTime12HoursProvider() {
		return new Object[][]{
		     new Object[] {"1:00am"}, new Object[] {"1:00 am"}, 
                     new Object[] {"1:00 AM"}, new Object[] {"1:00pm"}, 
                     new Object[] {"1:00 pm"},new Object[] {"1:00 PM"},
		     new Object[] {"12:50 pm"}
		};
	}
	
	@DataProvider
	public Object[][] InvalidTime12HoursProvider() {
		return new Object[][]{
			 new Object[] {"0:00 am"},new Object[] {"10:00  am"},
			 new Object[] {"1:00"},new Object[] {"23:00 am"},
			 new Object[] {"1:61 pm"},new Object[] {"13:00 pm"},
			 new Object[] {"001:50 pm"},new Object[] {"10:99 am"},
			 new Object[] {"01:00 pm"}, new Object[] {"1:00 bm"}
		};
	}
	
	@Test(dataProvider = "ValidTime12HoursProvider")
	public void ValidTime12HoursTest(String time) {
	   boolean valid = time12HoursValidator.validate(time);
	   System.out.println("Time12Hours is valid : " + time + " , " + valid);
	   Assert.assertEquals(true, valid);
	}
	
	@Test(dataProvider = "InvalidTime12HoursProvider", 
                 dependsOnMethods="ValidTime12HoursTest")
	public void InValidTime12HoursTest(String time) {
	   boolean valid = time12HoursValidator.validate(time);
	   System.out.println("Time12Hours is valid : " + time + " , " + valid);
	   Assert.assertEquals(false, valid); 
	}	
}

Unit Test – Result


Time12Hours is valid : 1:00am , true
Time12Hours is valid : 1:00 am , true
Time12Hours is valid : 1:00 AM , true
Time12Hours is valid : 1:00pm , true
Time12Hours is valid : 1:00 pm , true
Time12Hours is valid : 1:00 PM , true
Time12Hours is valid : 12:50 pm , true
Time12Hours is valid : 0:00 am , false
Time12Hours is valid : 10:00  am , false
Time12Hours is valid : 1:00 , false
Time12Hours is valid : 23:00 am , false
Time12Hours is valid : 1:61 pm , false
Time12Hours is valid : 13:00 pm , false
Time12Hours is valid : 001:50 pm , false
Time12Hours is valid : 10:99 am , false
Time12Hours is valid : 01:00 pm , false
Time12Hours is valid : 1:00 bm , false
PASSED: ValidTime12HoursTest("1:00am")
PASSED: ValidTime12HoursTest("1:00 am")
PASSED: ValidTime12HoursTest("1:00 AM")
PASSED: ValidTime12HoursTest("1:00pm")
PASSED: ValidTime12HoursTest("1:00 pm")
PASSED: ValidTime12HoursTest("1:00 PM")
PASSED: ValidTime12HoursTest("12:50 pm")
PASSED: InValidTime12HoursTest("0:00 am")
PASSED: InValidTime12HoursTest("10:00  am")
PASSED: InValidTime12HoursTest("1:00")
PASSED: InValidTime12HoursTest("23:00 am")
PASSED: InValidTime12HoursTest("1:61 pm")
PASSED: InValidTime12HoursTest("13:00 pm")
PASSED: InValidTime12HoursTest("001:50 pm")
PASSED: InValidTime12HoursTest("10:99 am")
PASSED: InValidTime12HoursTest("01:00 pm")
PASSED: InValidTime12HoursTest("1:00 bm")

===============================================
    com.mkyong.regex.Time12HoursValidatorTest
    Tests run: 17, Failures: 0, Skips: 0
===============================================

===============================================
mkyong
Total tests run: 17, Failures: 0, Skips: 0
===============================================

Reference

http://en.wikipedia.org/wiki/12-hour_clock

Want to learn more about regular expression? Highly recommend this best and classic book – “Mastering Regular Expression”