php – Difference in hours between days using carbon

Question:

When checking the difference in hours between today and tomorrow, I receive the value of 6 which refers to the number of hours until 00:00 today;

$t = \Carbon\Carbon::tomorrow();
$n = \Carbon\Carbon::now();
$n->diffInHours($t); // 6

But when I try to check with dates in the past I get an even larger number;

$y = \Carbon\Carbon::yesterday();
$n->diffInHours($n) // 41

Why do the values ​​have this difference and why does "yesterday's" date have a greater positive difference than tomorrow's?

Answer:

Let's create a minimal example, to illustrate and show what happens:

In the first result which is the code print_r( \Carbon\Carbon::yesterday() );

Carbon\Carbon Object
(
    [date] => 2018-01-14 00:00:00.000000
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)

and in its result which is the code: print_r( \Carbon\Carbon::now() );

Carbon\Carbon Object
(
    [date] => 2018-01-15 16:51:15.992829
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)

the difference in hours of these two results by the code:

print_r( \Carbon\Carbon::now()->diffInHours( \Carbon\Carbon::yesterday() ) );

is the value of 40 , because the first result to arrive on the 15th has 24 hours + 16 hours from the second is the value of 40 hours of difference .

In the other than the general code as a minimum example:

print_r( \Carbon\Carbon::tomorrow() );
print_r( \Carbon\Carbon::now() );
print_r( \Carbon\Carbon::now()->diffInHours( \Carbon\Carbon::tomorrow() ) );

Exit:

Carbon\Carbon Object
(
    [date] => 2018-01-16 00:00:00.000000
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)
Carbon\Carbon Object
(
    [date] => 2018-01-15 16:56:28.216548
    [timezone_type] => 3
    [timezone] => America/Sao_Paulo
)

there is a difference of 7 hours because the day 15/01/2018 16:56:28.216548 to arrive on 16/01/2018 there are 7 hours to go .


To find out if one date and time is greater than the other :

\Carbon\Carbon::setLocale('pt_BR');

$result = \Carbon\Carbon::create(2012, 9, 6, 0, 0, 0)
            ->gt( \Carbon\Carbon::create(2012, 9, 6, 0, 0, 0) );

var_dump($result); // saída bool(false)
Scroll to Top