Problem when calculating difference between two dates in PHP

0

Can someone tell me why this code prints 12 ?

$_POST['sdate'] in this example is: 2018-10-31

$_POST['date'] in this example is: 2019-07-13

$startDate = DateTime::createFromFormat('Y-m-d', $_POST['sdate']);
$endDate = DateTime::createFromFormat('Y-m-d', $_POST['date']);

$dif2 = date_diff($startDate, $endDate);
$diff2 = $dif2->format('%d');

echo $diff2;

This calculates me badly with almost any date, but I have put that example because it is very clear that it is not correct (as far as I know).

Thank you very much.

    
asked by ByBrayanYT - Tops y más 29.10.2018 в 20:49
source

2 answers

2

The problem is how you are showing it, instead of using% d use% a.

Here I copy the code working, it returns 255 days:

$startDate = DateTime::createFromFormat('Y-m-d', '2018-10-31');
$endDate = DateTime::createFromFormat('Y-m-d', '2019-07-13');

$dif2 = date_diff($startDate, $endDate);
$diff2 = $dif2->format('%a');

echo $diff2;

Good luck!

    
answered by 29.10.2018 / 21:00
source
0

try this to see

function validate_date($d1,$d2){
    $d_1 = explode("-", $d1);
    $d_2 = explode("-", $d2);

for($i = 0; $i <= count($d_1) -1; $i++)
    if($d_1[$i] != $d_2[$i]){
        return false;       
    }
    return true;    
}

if(validate_date('2018-10-31','2018-11-31')){
    echo "es igual";
}
    
answered by 29.10.2018 в 21:03