How to check date using PHP

If the date is sent on the form in the following format $month=2, $day=31, $year= 2010 . How can I check using the PHP date function if it is a valid date or not? Thanks.

+6
php
source share
5 answers

http://php.net/manual/en/function.checkdate.php

The checkdate function is the first google result from the search "php check date"

In your case, the use will be:

 checkdate($month, $day, $year); 
+13
source share
 <?php function validateDate($date, $format = 'Ymd H:i:s'){ $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; } ?> var_dump(validateDate('2012-02-28 12:12:12')); # true var_dump(validateDate('2012-02-30 12:12:12')); # false var_dump(validateDate('2012-02-28', 'Ym-d')); # true var_dump(validateDate('28/02/2012', 'd/m/Y')); # true var_dump(validateDate('30/02/2012', 'd/m/Y')); # false 
Function

was copied from this or php.net

+3
source share

Try checkdate () http://php.net/manual/en/function.checkdate.php

 checkdate($month, $day, $year); 

returns true if the date is valid / false otherwise

+2
source share
 bool checkdate ( int $month , int $day , int $year ) 
+1
source share

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; } 
0
source share

All Articles