Here's what I came up with to combine the rigor of checkdate () with the convenience of DateTime (it converts entries like "next thursday" or "2 weeks ago")
If the input string is invalid, it returns false. Empty dates are returned as zero, and non-empty dates are formatted in the MySQL "Ymd" style.
/** * @return variant null for empty date, mysql date string for valid date, or false for invalid date string */ function myCheckDate($date) { $result=false; if($date=='') { $result=null; } else { //Best of both worlds // - flexibility of DateTime (next thursday, 2 weeks ago, etc) // - strictness of checkdate (2000-02-31 is not allowed) $m=false; $d=false; $y=false; $parts=date_parse($date); if($parts!==false) { $m=$parts['month']; $d=$parts['day']; $y=$parts['year']; } if($m!==false && $d!==false) { if($y===false) $y=date('Y'); //Default to this year //Try for a specific date - this catches bad entries like 'feb 31, 2000' if(checkdate($m,$d,$y)) $result=sprintf('%04d-%02d-%02d',$y,$m,$d); } else { //Try for something more generic - this allows entries like 'next thursday' $dt=false; try{ $dt=new \DateTime($date); }catch(\Exception $e){ $dt=false; } if($dt!==false) $result=$dt->format('Ym-d'); } } return $result; }
Jon hulka
source share