How to validate time in 24 | Java program to validate the time in 24 - hour format using Regular Expression . ; Function to validate the time in 24 - hour format ; Regex to check valid time in 24 - 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 : ; Test Case 5 :
import java . util . regex . * ; class GFG { public static boolean isValidTime ( String time ) { String regex = " ( [01 ] ? [0-9 ] ▁ 2[0-3 ] ) : [ 0-5 ] [ 0-9 ] " ; Pattern p = Pattern . compile ( regex ) ; if ( time == null ) { return false ; } Matcher m = p . matcher ( time ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = "13:05" ; System . out . println ( str1 + " : ▁ " + isValidTime ( str1 ) ) ; String str2 = "02:15" ; System . out . println ( str2 + " : ▁ " + isValidTime ( str2 ) ) ; String str3 = "24:00" ; System . out . println ( str3 + " : ▁ " + isValidTime ( str3 ) ) ; String str4 = "10:60" ; System . out . println ( str4 + " : ▁ " + isValidTime ( str4 ) ) ; String str5 = "10:15 ▁ PM " ; System . out . println ( str5 + " : ▁ " + isValidTime ( str5 ) ) ; } }