PHP中strtotime函数存在Bug

5

我的代码中使用strtotime()函数分离日期时遇到了问题。当我使用“/”时,格式变成了月-日-年,而当我使用“-”时,格式变成了日-月-年。 我正在尝试在用户输入日期时同时使用“/”和“-”
我已经使用preg_match验证了用户是否输入了“-”或“/” 非常感谢能够帮助我的人。
下面是我的代码:

<?php
$date1=$_GET["q1"];
$date2= $_GET["q2"];
// To check date format for From date   
function checkDateFormat1($date1)
{
//match the format of the date
    if( (preg_match(" /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/", $date1,$parts)) || (preg_match(" /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/", $date1,$parts)) )
{
    //check weather the date is valid of not
    //if(checkdate($parts[2],$parts[3],$parts[1]))
    if(checkdate($parts[2],$parts[1],$parts[3]))
    return true;
    else
    return false;
}
else
return false;
}

 // To check the format for To date         
 function checkDateFormat2($date2)
{

if((preg_match(" /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/", $date2,$parts))||(preg_match(" /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/", $date2,$parts)))
{
    //check weather the date is valid of not
    //if(checkdate($parts[2],$parts[3],$parts[1]))
    if(checkdate($parts[2],$parts[1],$parts[3]))
    return true;
    else
    return false;
}
else
return false;
 }                      

if ((checkDateFormat2($date2) && checkDateFormat1($date1))==1)
{
if ($date1==$date2)
{
    $days="1";
    echo $days;
    exit;
}
else
{   
    $difference =(strtotime($date2) - strtotime($date1));
    //calculate the number of days
    $days = round(((($difference/60)/60)/24), 0);
}
 }
 else
 {
     echo "Invalid Date Format"."<br>";
echo "Please make sure that your for date format is MM-DD-YYYY";

exit;
        }

  if ($days<0)
 {
echo "From date cannot be greater than to date";

}   
else
{
$days++;
echo $days;


}   
 ?>

你试过 DateTime::getTimestamp 吗?只是出于好奇。 - Zathrus Writer
尝试使用PHP的 $date = DateTime::createFromFormat('Y-m-d',$YourDateString); - Seeker
3个回答

12

它的工作原理与 strToTime() 函数的预期工作方式完全相同。以下是来自 PHP 手册的说明:

注意:

使用m/d/yd-m-y格式表示的日期,会根据不同组件之间的分隔符进行消歧义: 如果分隔符是斜杠(/),则假定为美国格式m/d/y; 而如果分隔符是破折号(-)或句点(.),则假定为欧洲格式d-m-y

为避免潜在的歧义,最好尽可能使用 ISO 8601 (YYYY-MM-DD) 格式的日期或 DateTime::createFromFormat() 函数。

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


3

查看标准日期格式。 只有这些格式strtotime()函数才能识别。

如果您的日期不是标准格式,请使用DateTime::createFromFormat

$d = DateTime::createFromFormat('d . Y - m', '15 . 2002 - 03');
echo $d->format('Y-m-d');

1

尝试使用PHP的$date = DateTime::createFromFormat('Y-m-d',$YourDateString);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接