Frank Helligberger Frank Helligberger - 1 month ago 9
PHP Question

Comparing dates in PHP paradox

I have the weirdest issue ever:

Trying to compare today's date with a date from

$_POST
. I treat the parameters as follows:

$str1 = date("d-m-Y");
$str2 = date("d-m-Y", strtotime($_POST['dateto']));


I compare the dates:

if ($str2 >= $str1) {
// doing what it is supposed to
}
else {
echo "error";
}


Now since this results in an "error", and I am a 100% sure I input a date that is later than today's one, I
echo
-ed the parameters it compares before the logical
if
and the result is:
02-11-2016 for
$str2
and 27-10-2016 for
$str1
. It is obvous that today is in October and the input date is in November, but it still runs the logical operator as false.

Any opinions?

Answer

Try this, use createFromFormat

$format = "d-m-Y";
$date1  = DateTime::createFromFormat($format, date('d-m-y'));
$date2  = DateTime::createFromFormat($format, $_POST['dateto']);    
if($date1 >= $date2){
// doing what it is supposed to
}
else {
echo "error";
}
Comments