Php confirming 24 hour time format

I allow users to select an hour from 00:00:00 to 23:00:00 and check if they send the correct format. Is there a regular expression or php function that checks the 24 hour format, for example. HH:MM:SS ?

I have found some examples of regular expressions, but the 24-hour time that I check is always set to 00 for minutes and seconds. Only the hour is changing.

for example

 18:00:00, 23:00:00, 01:00:00 
+8
date php time
source share
5 answers

This corresponds to 24 hours, including seconds

 ([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9] 

If you want only 00 minutes and seconds, then

 ([01]?[0-9]|2[0-3]):00:00 
+19
source share

Here his finished sample is ready for use.

 $myTime = '23:00:00'; $time = preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $myTime); if ( $time == 1 ) { // make a error! } else { // make a error! } 
+3
source share

try it

 $time="23:00:00"; preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $time); 
+2
source share

Will it be RegEx? You can easily use the PHP strtotime function to check dates and times (also works without a date). strtotime returns false ( -1 to PHP 5.1) if the given time is not valid. Therefore, do not forget to use the operand === !

 if (strtotime("12:13") === false) { echo("Wrong Time!"); } // Echos nothing if (strtotime("19:45") === false) { echo("Wrong Time!"); } // Echos nothing if (strtotime("17:62") === false) { echo("Wrong Time!"); } // Echos 'Wrong Time!' 
+1
source share

It worked like a charm for me.

 $time = "23:59:60"; preg_match("/^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $time) 
0
source share

All Articles