Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Carbon diffInMonths

I have a problem with PHP Carbon diffInMonths function. In some cases I got wrong result. For example:

$start = \Carbon\Carbon::create(2017, 4, 1);
$end   = \Carbon\Carbon::create(2017, 5, 1);

echo $start->diffInMonths($end);

I should get 1 but I got 0. I use PHP 7.1 and Laravel 5.4.

Does anybody have a same issue? How can I fix it? Thank you for your help!

like image 527
Márk Pásztor Avatar asked May 09 '17 22:05

Márk Pásztor


2 Answers

$start = \Carbon\Carbon::create(2017, 4, 1);
$end   = \Carbon\Carbon::create(2017, 5, 1);

echo round($start->floatDiffInMonths($end));
like image 114
白海印 Avatar answered Oct 12 '22 10:10

白海印


As the Carbon issue on the github says it's a bug. Here is more.

<?php
$d1 = new DateTime("2015-03-01 00:00:00.000000", new DateTimeZone('Europe/London'));
$d2 = new DateTime("2015-05-01 00:00:00.000000", new DateTimeZone('Europe/London'));

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

print_r($diff);

output

DateInterval Object ( [y] => 0 [m] => 1 [d] => 30 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 61 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
like image 44
LF00 Avatar answered Oct 12 '22 11:10

LF00