Search code examples
laraveldatetimephp-carbondatetime-conversion

How to convert hours to seconds in carbon PHP API extension


I want to convert "2 hours 11 mins"(string) to seconds in carbon is there's any way convert that string format into seconds in carbon? I am stuck with this, couldn't find a solution yet Thank you in advance...


Solution

  • Carbon has a useful modify() function:

    https://carbon.nesbot.com/docs/#api-addsub

    This function can handle a number of "magic" durations to change a Date to another one. Since Carbon works with time stamps, you'll need a base and an modified one, then compare them:

    $base = Carbon\Carbon::now();                         // 2020-11-03 19:04:49.140462 UTC (+00:00)
    $modified = $base->copy()->modify('2 hours 11 mins'); // 2020-11-03 21:15:49.140462 UTC (+00:00),
    $diff = $base->diffInSeconds($modified);              // 7860
    

    Note: the string passed to modify() can fail, but you'll receive an error if it does.