Carbon Date Time Hours Comparison

11,609

From Carbon Docs

$today =  Carbon::now(new \DateTimeZone('Asia/Jakarta'));
$last = Carbon::parse(EmergencyOrder::select('CreatedDate')
                    ->orderBy('CreatedDate', 'desc')
                    ->first()->CreatedDate); //if there are no records it will fail

//check for equal
var_dump($today->eq($last));                     // bool(false)
//check for not equal
var_dump($today->ne($last));                     // bool(true)
//check $today < $last
var_dump($today->gt($last));                     // bool(false)
//check $today <= $last
var_dump($today->gte($last));                    // bool(false)
//check $today > $last
var_dump($today->lt($last));                     // bool(true)
//check $today >= $last
var_dump($today->lte($last));                    // bool(true)

And if you need the diference

$today->diffInHours($last);
$today->diffInMinutes($last);
$today->diffInDays($last);
Share:
11,609
Cookie
Author by

Cookie

Updated on June 14, 2022

Comments

  • Cookie
    Cookie almost 2 years

    How do I compare the hours between these two?

    $today = Carbon::now(new \DateTimeZone('Asia/Jakarta'))->toDateTimeString();
    

    and

    $last = EmergencyOrder::select('CreatedDate')
      ->orderBy('CreatedDate', 'desc')
      ->first();
    
  • Cookie
    Cookie over 6 years
    ho thanks for the reply, btw this doesnt work, here's the error: (1/1) FatalThrowableError Call to a member function diffInHours() on string
  • aaron0207
    aaron0207 over 6 years
    I miss to init the $today and $last variables, check it