Search code examples
phplaraveldatetimephp-carbon

How to convert a time (01:10:00) to 1h 10m short code in Laravel


I have to convert a time 01:10:00 to 1h 10m and also i have to exclude if the hours Or minutes is zero.

Ex:

01:10:00 --> 1h 10m

01:00:00 ---> 1h

00:10:00 ---> 10m

I have tried like this:

date('g', strtotime('01:10:00')).'h'.' '.date('i', strtotime('01:10:00')).'m'

But is there any other simple way to achieve this. using Carbon::parse()->Something() something like that

Kindly help me how to achieve this


Solution

  • Use can use a mix of Carbon's createFromTimeString and diffForHumans.

    use Carbon\CarbonInterface;
    use Illuminate\Support\Carbon;
    
    $result = Carbon::createFromTimeString('01:10:00')
        ->diffForHumans(Carbon::today(), CarbonInterface::DIFF_ABSOLUTE, true, 3);