How to validate Time in 12 Hours format with regular expression in java

Content:

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

 

Code :
package com.codewr.javacore.regular.expression;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

/**

 *

 * @author codewr

 */

public class Time12HoursValidator {

 

    private static final String TIME12HOURS_PATTERN

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

 

    public static void main(String[] args) {

        Time12HoursValidator time12HoursValidator = new Time12HoursValidator();

        //check  time validate

        boolean isValid = time12HoursValidator.validate("1:00pm");

        System.out.println("time valid is " + isValid);

    }

 

    /**

     * Validate time with regular expression

     *

     * @param time time for validation

     * @return true valid time, false invalid time

     */

    public boolean validate(final String time) {

        Pattern pattern = Pattern.compile(TIME12HOURS_PATTERN);

        Matcher matcher = pattern.matcher(time);

        return matcher.matches();

 

    }

}

Code UnitTest:

Time valid

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

Time invalid

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

 

import com.codewr.javacore.regular.expression.Time12HoursValidator;

import org.testng.Assert;

import org.testng.annotations.*;

 

/**

 * Time 12 hours format validator Testing

 *

 * @author codewr

 *

 */

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);

    }

}

Output:

Running Time12HoursValidatorTest

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

Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.553 sec

 

Results :

 

Tests run: 17, Failures: 0, Errors: 0, Skipped: 0

Note: file pom.xml add maven

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>6.8</version>

<scope>test</scope>

</dependency>