PHP Carbon diffInMonths
Asked Answered
H

2

6

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!

Hypercorrect answered 9/5, 2017 at 22:34 Comment(0)
S
3

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

echo round($start->floatDiffInMonths($end));
Streetman answered 4/3, 2020 at 9:44 Comment(1)
Yes, but this method is available since Carbon 2.x. Carbon 1.x has not this method.Trochilus
C
1

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 )
Cristinacristine answered 9/5, 2017 at 22:42 Comment(2)
Thank you! Is there a workaround or how can I solve this problem?Encircle
@MárkPásztor You can use this https://mcmap.net/q/822268/-find-month-difference-in-php-duplicateCristinacristine

© 2022 - 2024 — McMap. All rights reserved.