<?php
/**
*
* Validate a Date
*
* @param string $date
* @param string format
* @return BOOL
*
*/
function Validatedate ($date, $format = ' yyyy-mm-dd ')
{
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
throw new Exception ("Invalid Date Format");
}
Return Checkdate ($m, $d, $y);
}
?>
Example Usage
<?php
echo validatedate (' 2007-04-21 ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 2007-21-04 ', ' yyyy-dd-mm ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 2007-21-04 ', ' yyyy/dd/mm ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 21/4/2007 ', ' dd/mm/yyyy ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 4/21/2007 ', ' mm/dd/yyyy ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 20070421 ', ' YYYYMMDD ')? ' Good '. "": ' Bad '. " ";
echo validatedate (' 04212007 ', ' yyyyddmm ')? ' Good '. "": ' Bad '. " ";
?>