How to validate time in 12 | Java program to validate the time in 12 - hour format using Regular Expression . ; Function to validate the time in 12 - hour format . ; Regex to check valid time in 12 - hour format . ; Compile the ReGex ; If the time is empty return false ; Pattern class contains matcher ( ) method to find matching between given time and regular expression . ; Return if the time matched the ReGex ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
import java . util . regex . * ; class GFG { public static boolean isValidTime ( String time ) { String regexPattern = " ( 1[012 ] ▁ [ 1-9 ] ) : " + " [ 0-5 ] [ 0-9 ] ( \\ s ) " + " ? ( ? i ) ( am ▁ pm ) " ; Pattern compiledPattern = Pattern . compile ( regexPattern ) ; if ( time == null ) { return false ; } Matcher m = compiledPattern . matcher ( time ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = "12:15 ▁ AM " ; System . out . println ( isValidTime ( str1 ) ) ; String str2 = "9:45PM " ; System . out . println ( isValidTime ( str2 ) ) ; String str3 = "1:15" ; System . out . println ( isValidTime ( str3 ) ) ; String str4 = "17:30" ; System . out . println ( isValidTime ( str4 ) ) ; } }