如果表单按以下格式提交日期$month=2, $day=31, $year= 2010
。如果有效日期,如何使用PHP日期函数进行验证?感谢。
答案 0 :(得分:13)
http://php.net/manual/en/function.checkdate.php
checkdate
功能是谷歌搜索“php validate date”
在您的情况下,用法是:
checkdate($month, $day, $year);
答案 1 :(得分:3)
<?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
复制
答案 2 :(得分:2)
尝试checkdate() http://php.net/manual/en/function.checkdate.php
checkdate($month, $day, $year);
如果date有效则返回true,否则返回
答案 3 :(得分:1)
bool checkdate ( int $month , int $day , int $year )
答案 4 :(得分:0)
以下是我将checkdate()的严格性与DateTime的便利性结合起来的结果(它转换了“下周四”或“2周前”等条目)
如果输入字符串无效,则返回false。空日期返回为null,非空日期的格式为MySQL样式'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;
}