Skip to content

Instantly share code, notes, and snippets.

@ryanmerritt
Created September 18, 2012 10:17
Show Gist options
  • Save ryanmerritt/3742435 to your computer and use it in GitHub Desktop.
Save ryanmerritt/3742435 to your computer and use it in GitHub Desktop.
PHP - Validate a date
/**
* Validate a date.
*
* Source: http://www.phpro.org/examples/Validate-Date-Using-PHP.html
*
* @param string $date
* @param string $format
* @return bool
*
*/
function validateDate($date, $format = 'DD/MM/YYYY')
{
switch ($format) {
case 'YYYY/MM/DD':
case 'YYYY-MM-DD':
list($y, $m, $d) = preg_split('/[-\.\/ ]/', $date);
break;
case 'YYYY/DD/MM':
case 'YYYY-DD-MM':
list($y, $d, $m) = preg_split('/[-\.\/ ]/', $date);
break;
case 'DD-MM-YYYY':
case 'DD/MM/YYYY':
list($d, $m, $y) = preg_split('/[-\.\/ ]/', $date);
break;
case 'MM-DD-YYYY':
case 'MM/DD/YYYY':
list($m, $d, $y) = preg_split('/[-\.\/ ]/', $date);
break;
case 'YYYYMMDD':
$y = substr($date, 0, 4);
$m = substr($date, 4, 2);
$d = substr($date, 6, 2);
break;
case 'YYYYDDMM':
$y = substr($date, 0, 4);
$d = substr($date, 4, 2);
$m = substr($date, 6, 2);
break;
default:
return FALSE;
}
return @checkdate($m, $d, $y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment