thumbnail

Converting Seconds to Minutes, Hours, Using Carbon & Laravel

Rawa Hamid
Rawa Hamid 1 min read
4 months ago August 1, 2024

Introduction

Ever stared at a number representing time in seconds and wished it were more human-friendly? Maybe you're tracking video playback duration or analyzing task completion times. Raw seconds don't always provide the most intuitive understanding. Luckily, Laravel, a popular PHP framework, offers built-in tools to simplify this conversion.

This article delves into converting seconds into a human-readable format using Laravel and its companion library, Carbon. Carbon empowers you to manipulate dates and times with ease. We'll explore two practical methods to achieve this conversion, making it a breeze to present time durations in a clear and concise way.

Using Carbon Instance

You can humanize the time from the seconds by the following

use Carbon\Carbon;
 
...
 
$seconds = 'your seconds';
 
// pass the seconds
$duration = Carbon::now()->subSeconds($seconds);
// create a placeholder
$placeholder = [
        'h' => $duration->format('H'),
        'm' => $duration->format('i'),
        's' => $duration->format('s')
];
 
// return the result
return __(':hh :mm :ss', $placeholder);

Using CarbonInterval Instance

If you want an easy way to show the duration, you can also use CarbonInterval

use Carbon\CarbonInterval;
 
...
 
$seconds = 'your seconds';
$interval = CarbonInterval::seconds($seconds);
 
return $interval->cascade()->forHumans(['short' => true]);

Using It Everywhere

If you want to use this method in your Laravel application, in multiple places. You may use it as a helper function, or as a blade directive.

Creating Helper Method

use Carbon\CarbonInterval;
 
function humanize($seconds): string {
    $interval = CarbonInterval::seconds($seconds);
 
    return $interval->cascade()->forHumans(['short' => true]);
}

Creating Custom Blade Directive

In your AppServiceProvider or your custom ServiceProvider, use this code inside the boot method

use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Blade;
 
public function boot()
{
    Blade::directive('humanizeDuration', function ($seconds) {
        // you can eaither return the created helper method
        return humanize($seconds);
 
        // or you can re-create the method here
        $interval = CarbonInterval::seconds($seconds);
 
        return $interval->cascade()->forHumans(['short' => true]);
    });
}

Conclusion

The methods presented in this article provide both flexibility and reusability. Choose the approach that best aligns with your project structure and coding style. With these techniques at your disposal, you can effectively communicate time-related information to your users in a clear and intuitive manner.