0

In Zend Framework 1.x there is Zend_Date() to validate (German Date and Time)

 /* input $df-dtDauer for example "16:59" */
 if(!Zend_Date::isDate($df_dtDauer_bis,'HH:mm')) {
  $this->_aMessage[] = 'ungültige "Endezeit": '.$df_dtDauer_bis;                           
  $bRet = false;   
 } 

How to do this with native PHP (5.3.x)?

  • You can use regex validator for this. Check thee SO posts [Php validating 24 hour time format](http://stackoverflow.com/questions/11005728/php-validating-24-hour-time-format) or [validate this format - “HH:MM”](http://stackoverflow.com/questions/3964972/validate-this-format-hhmm) – Nandakumar V Jan 21 '15 at 11:21
  • PHP has a [`DateTime`](http://php.net/DateTime) module, which supports format specifiers and implicitly verifies correct input. – mario Jan 21 '15 at 11:21

1 Answers1

2

You can also use the DateTime as suggested by mario.

A function like this will help you to validate the format.

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true  

function was copied from this answer or php.net

Community
  • 1
  • 1
Nandakumar V
  • 4,317
  • 4
  • 27
  • 47