简体   繁体   中英

Php, how to determine if a string is a time?

I want to detect if a string is a time ( 00:18:31 ). I know about strtotime() but it also detects " now " as OK, and so on. I need a real solution.

Try this:-

if (DateTime::createFromFormat('H:i:s', $yourtimeString) !== FALSE) {
  echo "it's a date";
}else{
echo "it's not a date";
}

Input:- 00:18:31 Output:- it's a date

Input:- now,NOW,now(),NOW() Output:- it's not a date

The validateTime() function checks whether the given string is a valid time. using DateTime class and createFromFormat() static method.


function validateTime($time, $format = 'H:i:s'){
  $t = DateTime::createFromFormat($format, $time);
  return $t && $t->format($format) === $time;
}
// Returns true
echo var_dump(validateTime("00:18:31"));
echo var_dump(validateTime("23:59:59"));
echo var_dump(validateTime("00:02:30"));
// Returns false
echo var_dump(validateTime("31:18:31"));
echo var_dump(validateTime("24:00:00"));
echo var_dump(validateTime("23:60:60"));

Explanation of $t->format($format) === $time is a test to check if the time is indeed a real time or not. for instance 23:59:59 is valid time but 24:00:00 is not.

We all know that 23:59:59 is the max acceptable Human time. and 24:00:00 is not. However, We can pretend it means the next day at 00:00:00 . that is what DateTime::createFromFormat do! when we give it a time exceed the maximum. It accept it by adding the remaining time to the next day.

For example today is 2021-05-14 23:59:59 and time to check if we give it to createFromFormat is 24:02:30 the date becomes next day 2021-05-15 00:02:30
We notice that 24:02:30 != 00:02:30 . So from that we can summarize that is not valid time. To be valid it must be the same!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM