Validate that input is in this time format - "HH:MM"
Solution 1
You can use regular expressions to check that.
for 12-hour:
preg_match("/^(?:1[012]|0[0-9]):[0-5][0-9]$/", $foo)
for 24-hour:
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $foo)
If you use a 24-hour clock going from 01:00 to 24:59, use
preg_match("/^(?:2[0-4]|[01][1-9]|10):([0-5][0-9])$/", $foo)
Solution 2
Simple function that validates a date (and/or time) without throwing exceptions. It takes the expected date format as a parameter:
function isValidDate(string $date, string $format = 'Y-m-d'): bool
{
$dateObj = DateTime::createFromFormat($format, $date);
return $dateObj && $dateObj->format($format) == $date;
}
How it works: it converts the input date into a PHP DateTime
object according to the passed $format
, then compares this object with the original input date.
If they match, the date is valid and has the expected format.
Some usage examples:
/* Valid Examples: */
isValidDate("2017-05-31");
isValidDate("23:15:00", 'H:i:s');
isValidDate("2017-05-31 11:15:00", 'Y-m-d h:i:s');
/* Invalid: */
isValidDate("2012-00-21");
isValidDate("25:15:00", 'H:i:s');
isValidDate("Any string that's not a valid date/time");
Solution 3
Let's imagine the time you want to check is $timeStr
and has to be the format H:i
according to the date specs.
Using a regex for this is IMHO silly. This is so much easier to read:
UPDATED
$timeStr = " 02:00"; //example of valid time, note whitespace
test($timeStr);
$timeStr = "23:59"; //valid
test($timeStr);
$timeStr = "24:00"; //invalid
test($timeStr);
$timeStr = "25:00"; //invalid
test($timeStr);
$timeStr = "16:61"; // invalid
test($timeStr);
//tests 23:59 hour format
function test($timeStr){
$dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr);
if ($dateObj !== false && $dateObj && $dateObj->format('G') ==
intval($timeStr)){
//return true;
echo 'valid <br/>';
}
else{
//return false;
echo 'invalid <br/>';
}
}
Solution 4
here is a code that check if the string is an hour between 00:00 and 23:59
$checked = false;
if (preg_match('/^\d{2}:\d{2}$/', $str)) {
if (preg_match("/(2[0-3]|[0][0-9]|1[0-9]):([0-5][0-9])/", $str)) {
$checked = true;
}
}
var_dump($checked );die;
Solution 5
Function that validates hours, minutes and seconds, according to the desired format:
function validTime($time, $format='H:i:s') {
$d = DateTime::createFromFormat("Y-m-d $format", "2017-12-01 $time");
return $d && $d->format($format) == $time;
}
How to use:
$valid = validTime("23","H");
$valid = validTime("23:59","H:i");
$valid = validTime("23:59:59","H:i:s");
$valid = validTime("23:59:59");
valid = true
$valid = validTime("25","H");
$valid = validTime("01:60","H:i");
$valid = validTime("01:20:61","H:i:s");
$valid = validTime("01:20:61");
valid = false
Comments
-
Catfish almost 4 years
I'm trying to use
preg_match
to validate that a time input is in this format - "HH:MM"