PHP difference date error

$startDate = new DateTime("2016-06-01");
$endDate = new DateTime("2016-06-30");
$diff = date_diff($startDate,$endDate);
$differenceYear = $diff->format("%y");
$differenceMonth = $diff->format("%m");
$difference = $differenceYear*12 + $differenceMonth;
echo $difference;

As a result, the code above outputs 0. But when I change these two dates to 2016-12-01 and 2016-12-31, the code gives 1 as the output. Why is this happening?

When I check this PHP editor of this code, it gives the correct answer. But when I copied it to my local machine, the answer showed the wrong character. The online editor has US / Pacific as a time zone. My computer has an Asia / Calcutta time zone . Both have the same version of PHP

+4
source share
2 answers

Using my default timezone ( Europe/Bucharest), a print_r($diff)produces:

DateInterval Object
(
    [m] => 1
    [d] => 0
    [days] => 30
)
# I removed the other components as they are irrelevant to the question
# and they are 0 anyway.

: "1 month 0 days" ( m d), 30 ( days).

Asia/Kolkata , :

DateInterval Object
(
    [m] => 0
    [d] => 30
    [days] => 30
)
# Again, all the other object properties are 0 and irrelevant for the question

: "0 30 ", 30 .


, ( days) (30) .

"1 0 " "0 ​​ 30 " .

" " ? 28 31 . , "1 0 " "0 28 ", "0 29 " a.s.o. .


" PHP" . PHP . "month" .

+3

. Id DateTime , 2016-12-01 00:00:00 +00:00, UTC.

$startDate = new DateTime("2016-12-01  00:00:00 +00:00");
$endDate = new DateTime("2016-12-31  00:00:00 +00:00"); 
$diff = date_diff($startDate,$endDate);
$differenceYear = $diff->format("%y");
$differenceMonth = $diff->format("%m");
var_dump($differenceYear,$differenceMonth);
$difference = $differenceYear*12 + $differenceMonth;
echo $difference;

(, Xatenevs, ; -)

+1

Source: https://habr.com/ru/post/1681456/


All Articles