Difference in hours between days using carbon

2

When checking the difference in hours between today and tomorrow I get the value of 6 which refers to the amount 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 values have such a difference and why the "yesterday" date has a bigger positive difference than tomorrow?

    
asked by anonymous 15.01.2018 / 18:10

1 answer

1

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

In the first result that 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 its result 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 40 , because the first result to arrive on the day 15 has 24 hours + 16 hours of the second is the value of 40 hours difference .

In 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() ) );

Output:

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
)

It has a 7 hour difference because the 2018 7 hours .

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)
    
15.01.2018 / 19:55