Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eludic's avatar

Carbon -- Difference between 2 dates

Date 1 = 15/07/2021

Date 2 = 25/03/2022

When I try to find the difference between 2 dates using Carbon's diffInDays() function I am getting 2 different results for the following:

$daysleft = $date1_carbon->diffInDays($date2_carbon);
$daysleft = $daysleft + 1;

For the above I get the output as 254

$daysleft = $date2_carbon->diffInDays($date1_carbon);
$daysleft = $daysleft + 1;

For the above I get 253

Which one is correct and which one should I be using?

0 likes
8 replies
tykus's avatar

Is there a time part to either datetime instance? How is the Carbon instance created???

eludic's avatar

@tykus Not really. They have been created as Carbon objects using the code

$date1_carbon = Carbon::createFromFormat('d/m/Y', $date1);
$date2_carbon = Carbon::createFromFormat('d/m/Y', $date2);
aschmelyun's avatar

Agreed with @tykus, without seeing the initialization of the $date1_carbon and $date2_carbon variables, it's really hard to answer this.

eludic's avatar

@Snapey

$date1_carbon = Carbon::createFromFormat('d/m/Y', $date1);
$date2_carbon = Carbon::createFromFormat('d/m/Y', $date2);

This one gives a difference.

MohamedTammam's avatar

@eludic No

=> Carbon\Carbon @1626349036 {#3701
     date: 2021-07-15 11:37:16.0 UTC (+00:00),
   }
>>> $date2 = Carbon::createFromFormat('d/m/Y', '25/03/2022');
=> Carbon\Carbon @1648208250 {#3696
     date: 2022-03-25 11:37:30.0 UTC (+00:00),
   }
>>> $date1->diffInDays($date2);
=> 253
>>> $date2->diffInDays($date1);
=> 253
Snapey's avatar

@eludic No it doesn't

$date1 = Carbon\Carbon::createFromFormat('d/m/Y','15/07/2021');

$date2 = Carbon\Carbon::createFromFormat('d/m/Y','25/03/2022');

echo $date1 . PHP_EOL;
echo $date2 . PHP_EOL;

$daysleft = $date1->diffInDays($date2);

echo $daysleft+1 . PHP_EOL;

$daysleft = $date2->diffInDays($date1);

echo $daysleft+1 . PHP_EOL;

Output:

2021-07-15 00:06:52
2022-03-25 00:06:52
254
254
eludic's avatar

Its weird but I am seeing a difference. Any specific fix I can use to remove this ambiguity?

Please or to participate in this conversation.