Search code examples
phplaravelphp-carbon

Calculate number of hours , minutes and seconds between two dates in laravel


Suppose we have to DateTime formatted date like this :

$started_at = '2016-07-05 12:29:16';
$ended_at = '2016-07-06 13:30:10';

Now I want to calculate number of hours , minutes and seconds of them like this :

15 hours and 50 minutes and 15 seconds

How Can I do that in simplest way in laravel and using Carbon.


Solution

  • Try this

    $t1 = Carbon::parse('2016-07-05 12:29:16');
    $t2 = Carbon::parse('2016-07-04 13:30:10');
    $diff = $t1->diff($t2);
    

    This will give you

    DateInterval {#727
         +"y": 0,
         +"m": 0,
         +"d": 0,
         +"h": 22,
         +"i": 59,
         +"s": 6,
         +"weekday": 0,
         +"weekday_behavior": 0,
         +"first_last_day_of": 0,
         +"invert": 1,
         +"days": 0,
         +"special_type": 0,
         +"special_amount": 0,
         +"have_weekday_relative": 0,
         +"have_special_relative": 0,
       }