-1

I Want how to compare two dates

I have this

$last_day = '2017-11-01';
$end = '18/03/2017';
$last_day = date('d/m/Y', strtotime($last_day));

            if($last_day < $end){
                echo "Is closed";
            }else{
                echo "Is Open";
            }

Return "Is Close"

What happens?

NARTONIC
  • 452
  • 10
  • 22

4 Answers4

2

You are comparing strings, not dates. Use DateTime() objects as they are comparable:

$last_day = new DateTime('2017-11-01');
$end      = DateTime::createFromFormat('d/m/Y', '18/03/2017');

if($last_day < $end){
  echo "Is closed";
}else{
  echo "Is Open";
}

If $fechas['last_day'] is in d/m/Y format you will have to change $last_day to use DateTime::createFromFormat() as well as that format will cause errors as dates using / are considered American and 18/3/2017 would be an invalid date.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • *`If $fechas['last_day']`* - [See my comment...](http://stackoverflow.com/questions/42857496/compare-two-dates-in-php-not-compare-correctly#comment72821142_42857496) John. – Funk Forty Niner Mar 17 '17 at 12:31
0

You are not compare two dates in date format. Please convert first in strtotime format after compare two date.

Please Try This

$last_day = '2017-11-01';
$end = strtotime('18/03/2017');
$last_day = strtotime(date('d/m/Y', strtotime($last_day)));

 if($last_day < $end){
    echo "Is closed";
 }else{
    echo "Is Open";
 }
Manish Jesani
  • 1,339
  • 5
  • 20
  • 36
0

First of all

try this

$last_day = '2017-11-01';
$end = '18/03/2017';
echo $last_day = date('d/m/Y', strtotime($fechas['last_day']));
if($last_day < $end){ echo "Is closed";}
else{ echo "Is Open";}

It will show you the correct value of $last date. And you can easily understand the problem. or You can convert both dates into timestamp and compare them.

$last_day = strtotime('2017-11-01');
$end = strtotime('18/03/2017');
$last_day = strtotime($fechas['last_day']);
if($last_day < $end){ echo "Is closed";}
else{ echo "Is Open";}
GYaN
  • 2,327
  • 4
  • 19
  • 39
-2

You cannot compare between string and date. Please convert both variable to date.

FPratama
  • 14
  • 3