日期不返回False的PHP IF语句


PHP IF statement with Date not returning False

我试图学习一点php,不能理解为什么2秒IF在这里执行。我有一个变量$theDate设置为接受欧洲日期4 May 2010。

$theDate = date('d-m-Y', strtotime("04-05-2010"));
echo "$theDate<br />";
if($theDate > "02-05-2010")
{
 echo "Greater than!<br />";
}
if($theDate > "02-05-2011")
{
 echo "Why am I showing<br />";
}
echo "Endof";

我现在只想使用if,而不是IF-Else等。但是为什么第二个IF在$theDate不大于02-05-2011的情况下执行,

thanks in advance,

我记得这是2014年。为什么不使用DateTime对象和做为什么不做正确的方式?

$raw = '04-05-2010';
$theDate= 'DateTime::createFromFormat('d-m-Y', $raw);
$raw2 = '02-05-2010';
$anotherDate = 'DateTime::createFromFormat('d-m-Y', $raw2);
echo 'theDatedate: ' . $theDate->format('m/d/Y') . "<br>";
echo 'anotherDate date: ' . $anotherDate ->format('m/d/Y') . "<br>";
if ($theDate > $anotherDate ) {
    echo "Greater than!<br />";
}

如果你正在学习php,请查看这个资源,值得一读。

要将日期作为字符串进行比较,只需使用UTC格式YYYY-MM-DD。如果你想将其作为整数进行比较你必须将其转换为秒或者从年开始比较然后与月进行比较等等——

使用字符串比较。因此,它首先查看第一个字符,如果它大于,则返回true。如果小于,则返回false。如果相等,移动到下一个字符。

您可以通过反向格式化字符串来解决此问题:Y-m-d。或者使用内置操作符:

if($time > strtotime($text))

其中$time以秒为单位。

您正在比较字符串。将日期转换为秒,然后进行比较,

$theDate = date('d-m-Y', strtotime("04-05-2010"));
echo "$theDate<br />";
if(strtotime($theDate) > strtotime("02-05-2010"))
{
 echo "Greater than!<br />";
}
if(strtotime($theDate) > strtotime("02-05-2011"))
{
 echo "Why am I showing<br />";
}
echo "Endof";