Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php validating 24 hour time format

Tags:

date

php

time

I'm allowing users to pick an hour from 00:00:00 to 23:00:00 and need to check if they submit the right format. Is there a regular expression or php function that validates a 24 hour format e.g. HH:MM:SS?

I found some regex examples but the 24 hour time I'm validating is always set to 00 for minutes and seconds. Only the hour varies.

For example

18:00:00, 23:00:00, 01:00:00
like image 471
CyberJunkie Avatar asked Jun 12 '12 22:06

CyberJunkie


5 Answers

This matches 24 hour time including seconds

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

If you only want 00 for minutes and seconds, then

([01]?[0-9]|2[0-3]):00:00
like image 98
sachleen Avatar answered Oct 11 '22 18:10

sachleen


Try This

$time="23:00:00";

preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $time);
like image 22
Emann Tumala Saligue Avatar answered Oct 11 '22 18:10

Emann Tumala Saligue


Check it by this function and you can add this function in CodeIgniter helper file of Laravel global helper functions file and call it more times

<?php
if(!function_exists("check_24_timeFormat")) {
    /**
     *
     * This for check time is in  24 time format  
     * 
     * @param string $time  [ $time => time in 24 hours format like 23:00:00 ]
     * @author Arafat Thabet <[email protected]> 
     * @return bool
     */
    function check_24_timeFormat($time){
        if (preg_match("#((0([0-9])|(1[0-9]{1})|(2[0-4])):([0-5])([0-9]):([0-5])([0-9]))#", $time)) {
            return true;
        }
        else
        {
            return false;
        }
    }
}
like image 23
Arafat Mutahar Avatar answered Oct 11 '22 17:10

Arafat Mutahar


Here its a final sample there are ready to be used.

$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!
}
like image 5
ParisNakitaKejser Avatar answered Oct 11 '22 18:10

ParisNakitaKejser


Has it to be a RegEx? You can easily use PHPs strtotime-function to validate dates and times (does also work without a date). strtotime returns false (-1 prior to PHP 5.1) if the given time isn't valid. Don't forget to use the === operand therefore!

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!'
like image 1
emale Avatar answered Oct 11 '22 18:10

emale