Home > Blockchain >  Carbon diffInMonth() returns wrong values
Carbon diffInMonth() returns wrong values

Time:01-10

I am developing a Laravel App and stumbled upon a problem with Carbon library, so I tested some things and found out that this code:

// Date Diff 1
$st1 = Carbon::parse("2022-11-01");
$fi1 = Carbon::parse("2023-04-01");
$diff1 = $st1->diffInMonths($fi1);

// Date Diff 2
$st2 = Carbon::parse("2022-11-01");
$fi2 = Carbon::parse("2023-03-01");
$diff2 = $st2->diffInMonths($fi2);

dd([
    'Diff 1' => "2022-11-01  ->  2023-04-01  =  $diff1",
    'Diff 2' => "2022-11-01  ->  2023-03-01  =  $diff2",
]);

returns this:

"Diff 1" => "2022-11-01  ->  2023-04-01  =  5"
"Diff 2" => "2022-11-01  ->  2023-03-01  =  3"

Can anyone possibly explain to me why it is working this way, or even a suggestion as to how I could fix it.

As to the versions, I am using Laravel 5.7 and PHP 7.2.5

CodePudding user response:

If you try that, you can find a similar problem:

$d1 = new \DateTime('2023-02-01');
$d2 = new \DateTime('2023-03-01');
$diff = date_diff($d1,$d2);
dump($diff->m); // months: 0
dump($diff->d); // days: 28
die;

The problem comes from PHP and not from Laravel, and is linked to the month of "February" (because there are only 28 days in February).

A solution could be to use this:

// Date Diff 1
$st1 = Carbon::parse("2022-11-01"); 
$fi1 = Carbon::parse("2023-04-01");
$diff1 = (int)$st1->floatDiffInMonths($fi1);

// Date Diff 2
$st2 = Carbon::parse("2022-11-01");
$fi2 = Carbon::parse("2023-03-03");
$diff2 = (int)$st2->floatDiffInMonths($fi2);

dd([
    'Diff 1' => "2022-11-01  ->  2023-04-01  =  $diff1", // 5
    'Diff 2' => "2022-11-01  ->  2023-03-01  =  $diff2", // 4
]);
  • Related