5

我在代码中使用 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;


}   
 ?>
4

3 回答 3

12

它的工作方式与 strToTime() 应该工作的方式完全相同。从 php 手册:

笔记:

m/d/ydmy格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美式m/d/y ;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲dmy格式。

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

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

于 2012-10-04T08:09:46.187 回答
3

看看标准日期格式。只有这种格式才能strtotime()识别。

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

$d = DateTime::createFromFormat('d . Y - m', '15 . 2002 - 03');
echo $d->format('Y-m-d');
于 2012-10-04T08:11:41.783 回答
1

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

于 2012-10-04T08:13:34.037 回答