subhra
subhra

Reputation: 173

Could not comapre two dates using PHP

I need to compare two given dates using PHP but as per my code its giving the wrong result. I am explaining my code below.

    $date=strtotime('18-05-2019 02:36 PM');
$stdate=date('d-m-Y H:i A',strtotime('18-05-2019'));
if($date==$stdate){
  echo 'same date';
}else{
  echo 'other date';

}

Here one date has date and time and other date has only date format. I need to compare the both dates using PHP. As per above code I am getting the result Other date which is wrong.

Upvotes: 0

Views: 35

Answers (2)

tshimkus
tshimkus

Reputation: 1181

Format the date with date() before you compare the values. You can take the UNIX timestamp generated by strtotime() and strip the time portion off:

$date=date( "Y-m-d", strtotime('18-05-2019 02:36 PM'));
$stdate=date( "Y-m-d", strtotime('18-05-2019'));

if($date==$stdate){
    echo 'same date';
}else{
    echo 'other date';
}

This has been tested and will echo 'same date'.

Upvotes: 1

Grant C.
Grant C.

Reputation: 356

The date string '18-05-2019' is equivalent to '18-05-2019 00:00 AM'. When no time is given, it is usually just set as midnight. Hours and minutes are taken into account when using strtotime(). So your code is actually performing correctly.

Upvotes: 1

Related Questions