3

我找到了一个 php 函数checkdate(),但奇怪的是它似乎只接受int $month , int $day , int $year. 但是我将日期作为字符串(示例"2012-06-13")传递,所以我想出了这个解决方法,因为我只允许以这种格式输入日期。不幸的是,我觉得这既不安全又不是解决问题的好方法:

function CheckAdditional($value)
{
    $data = explode("-", $value);

    return checkdate($data[1], $data[2], $data[0]);
}

问题:有没有更好的方法来检查日期是否有效?

4

6 回答 6

2

你可以试试:

function checkDateFormat($date){  
//match the format of the date  
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))  {    
    //check weather the date is valid of not        

    if(checkdate($parts[2],$parts[3],$parts[1]))          
       return true;        
    else         
       return false;  
    }  
else    
return false;}

学分:http ://roshanbh.com.np/2008/05/date-format-validation-php.html

于 2012-06-13T15:56:59.877 回答
1

为了安全起见,您可以这样做

date("Y-m-d", strtotime($yourdatestr));

这样,即使格式可能是错误的,它在大多数情况下都会纠正它。

于 2012-06-13T15:59:09.043 回答
1
<?php

function CheckAdditional($value)
{
    return date('Y-m-d', strtotime($value)) == $value;
}

?>

经过我和试图帮助我回答的人的多次测试后,我想出了这个非常适合我的解决方案,并且在我看来既简单又非常可靠,因为到目前为止没有人能够证明它是错误的。

于 2012-06-18T07:16:20.860 回答
1
$jahr = (int) $_POST['jahr'];
$monat =  (int) $_POST['monat'];
$tag = (int) $_POST['tag'];
$datum = "$tag. $monat. $jahr";

if (checkdate($monat, $tag, $jahr) == FALSE) {
    $allesok = false;
    $fehlermeldung .= "<p class='fehler'>Ungültiges Datum $datum!</p>";
}
于 2017-06-10T10:57:49.523 回答
0

如果您将用户输入限制为仅在一种格式下有效(本地化呢?),那么您可以自己解析输入,使用正则表达式函数或将输入拆分为“-”并检查它是否变成三位数的数组……</p>

于 2012-06-13T15:58:38.613 回答
0
function DDC($dates){ // Date Day Control
    $dy = substr($dates,0,4);
    $dm = substr($dates,5,2);
    $dd = substr($dates,8,2);
    for($i=0; $i<3; $i++){
        if(!checkdate($dm,$dd,$dy)){
            $dd--;
        }else{$i=3;}
    }
    return $dy.'.'.$dm.'.'.$dd;
}
echo DDC('2013.02.31');
//2013.02.28
于 2013-07-16T14:46:21.460 回答