我在代码中使用 strtotime() 来分隔日期时遇到问题。当我使用“/”时,格式变为 mm-dd-yyyy,当我使用“-”时,格式变为 dd-mm-yyyy。
当用户输入我使用 preg_macth 验证用户给出的天气的日期时,我试图同时使用“/”和“-” - 或者 / 非常感谢可以帮助我的人。
我的代码如下
<?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;
}
?>