Carbon Date Time Hours Comparison

Cookie picture Cookie · Oct 3, 2017 · Viewed 8.8k times · Source

How do I compare the hours between these 2?

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

and

$last = EmergencyOrder::select('CreatedDate')
                        ->orderBy('CreatedDate', 'desc')
                        ->first();

Answer

aaron0207 picture aaron0207 · Oct 3, 2017

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