MatcherPattern

Validate Time In 12 Hours Format with Java Regular Expression example

In this tutorial we are going to see how to validate 12 Hours time format with Java Regular Expressions.The basic policy about the 12 hours format is that:

  • It should start with two digits from 00 to 12.
  • It must be followed by ‘:’.
  • It should be followed by two digits from 00 to 59.
  • Then, only one white space should follow, although this is optional.
  • Finally, there should be ‘am’, ‘pm’, ‘AM’ or ‘PM’.

 
 
 
So this is the regular expression we are going to use for 12 hours format validation:

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

You can take a look at the Pattern class documentation to learn how to construct your own regular expressions according to your policy.

1. Validator class

This is the class that we are going to use for 12 hours time format validation.

Time12hFormatValidator.java:

package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Time12hFormatValidator{

	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 Time12hFormatValidator(){
		  pattern = Pattern.compile(TIME12HOURS_PATTERN);
	  }

	  public boolean validate(final String time){		  
		  matcher = pattern.matcher(time);
		  return matcher.matches();	    	    
	  }
}

2. Unit Testing our Time12hFormatValidator class

For unit testing we are going to use JUnit. Unit testing is very important in these situations because they provide good feedback about the correctness of our regular expressions. You can test your program and reassure that your regular expression meets the rules on your policy about the form of 12 hour time format.

This is a basic test class:

Time12hFormatValidatorTest.java:

package com.javacodegeeks.java.core;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class Time12hFormatValidatorTest {

	private String arg;
	private static Time12hFormatValidator time12hFormatValidator;
	private Boolean expectedValidation;

	public Time12hFormatValidatorTest(String str, Boolean expectedValidation) {
		this.arg = str;
		this.expectedValidation = expectedValidation;
	}

	@BeforeClass
	public static void initialize() {
		time12hFormatValidator = new Time12hFormatValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {
				{ "00:00 am", false },    // 12h format is out of range
				{ "2.20", false },      // wrong format
				{ "17:10 pm", false },    // it is 12 hour format!
				{ "1:20", false },        // there is no pm am

				{ "9:35 pm", true },                         
				{ "7:30 AM", true },
				{ "12:01 am", true } };

		return Arrays.asList(data);
	}

	@Test
	public void test() {
		Boolean res = time12hFormatValidator.validate(this.arg);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Time Format "+arg+ " is " + validv);
		assertEquals("Result", this.expectedValidation, res);

	}

}

Output:

Time Format 00:00 am is invalid
Time Format 2.20 is invalid
Time Format 17:10 pm is invalid
Time Format 1:20 is invalid
Time Format 9:35 pm is valid
Time Format 7:30 AM is valid
Time Format 12:01 am is valid

 
This was an exampl on how to validate time in 12 Hours format with Java Regular Expression.

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button