PHP日期比较(2周)

时间:2014-12-04 09:57:56

标签: php date

$todaysDate = date("Y-m-d");
$maxBookingDate=strtotime('+2 weeks', $todaysDate);
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST["Date"]);
$tableDate =$dateEntered->format('Y-m-d');
if ($tableDate < $todaysDate){
    echo "Date must be in the future";
}
if ($tabledate > $maxBookingDate){
    echo "Date must be no more than 2 weeks in advance";
}

日期比较以确保用户输入的日期不超过两周不起作用,我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以直接使用DateTime个类,以便更容易比较:

$todaysDate = new DateTime();
$maxBookingDate = new DateTime('+2 weeks');
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST['Date']);
if ($dateEntered < $todaysDate){
    echo "Date must be in the future";
} elseif ($dateEntered > $maxBookingDate){
    echo "Date must be no more than 2 weeks in advance";
}

在您的代码中:

$todaysDate是一个字符串,您在strtotime()内输入它作为第二个参数,这是不正确的用法。第二个参数需要数值(时间戳)。

在if else语句中,您需要比较字符串。你应该将它们作为时间戳或DateTime对象进行比较,就像上面的答案一样。