Reputation: 147
If a date is submitted by form in following format, $month=2, $day=31, $year= 2010
. How can i verify using PHP date function if it is valid date or not? Thanks.
Upvotes: 7
Views: 23590
Reputation: 8809
http://php.net/manual/en/function.checkdate.php
The checkdate
function is the first result in google from the search "php validate date"
In your case, the usage would be:
checkdate($month, $day, $year);
Upvotes: 14
Reputation: 504
<?php
function validateDate($date, $format = 'Y-m-d 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', 'Y-m-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 answer or php.net
Upvotes: 4
Reputation: 1319
Here's what I've come up with to combine the strictness 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 null, and non-empty dates are formatted MySQL style 'Y-m-d'.
/**
* @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('Y-m-d');
}
}
return $result;
}
Upvotes: 0
Reputation: 3556
Try checkdate() http://php.net/manual/en/function.checkdate.php
checkdate($month, $day, $year);
returns true if date is valid / false otherwise
Upvotes: 2
Reputation: 7494
bool checkdate ( int $month , int $day , int $year )
Upvotes: 1