error when using the diff on dates with php?

0

I'm currently using the diff command in php to make a difference of two months, but that difference comes out but it's wrong it's not the correct one:

Date today: 8-03-18 future date: 07-05-18

This is the result that I get:

The middle box is the one that is supposed to pretend as a counter in reverse between both dates, but instead of saying 10 months it should say 1 month and 29 days.

Code

<?php

$hoy = date('j-m-y');
$despues='07-05-18';
$horafutura='00:00';

$d1 = new DateTime($hoy);
$d2 = new DateTime($despues);


$interval = $d2->diff($d1);


echo '<div class="horario">'.$interval->format('%y years %m months %d days').'</div>';

 ?>
    
asked by David 08.03.2018 в 17:48
source

2 answers

1

Hello! Maybe it has to do with the format in which the dates go when instantiated as DateTime objects. My suggestion is that you use the classic year-month-day format, just to try.

$hoy = date('Y-m-d');
$despues='2018-05-07';
$horafutura='00:00';

(If you subtract the dates as you do now, assuming that PHP thinks that the first value is the year, the second, the month, and the third, the day, they may give you the 10 months ...) .

    
answered by 08.03.2018 / 19:43
source
0

The problem is because DateTime is not correctly recognizing the format of the entered date .

Solution:

You could use DateTime::createFromFormat to indicate the format in which the date comes and thus be able to calculate correctly the difference.

In addition, you must calculate the difference from $d1 , otherwise the result would be one more day.

Example:

$hoy = date('j-m-y');
$despues='07-05-18';
$horafutura='00:00';

$d1 = DateTime::createFromFormat('j-m-y', $hoy);
$d2 = DateTime::createFromFormat('j-m-y', $despues);

$interval = $d1->diff($d2);


echo '<div class="horario">'.$interval->format('%y years %m months %d days').'</div>';
    
answered by 08.03.2018 в 19:40