$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";
}
Date comparison to make sure that the date a user enters is no more than two weeks in advance isn't working, what have I done wrong?
You can just use DateTime
classes all through out so that its easier to compare:
$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";
}
In your code:
$todaysDate
is a string, and you fed it inside strtotime()
as your second parameter which is incorrect usage. The second parameter requires numeric value (timestamp).
Inside your if else statement, you're comparing strings. You should be comparing them as timestamps or DateTime objects instead, like the answer above.