MahmoudMonem's avatar

How to calculate total time duration using Carbon

I have a courses that has many lessons .. The lessons table has duration timestamp field .. I would like to calculate the total number of hours for a specific course. I tried to check for this but mostly people are calculating differences between two times.

course id	lesson_title	lesson_duration
-------------------------------------------------------------------
1	                 Intro	        00:16:43
1	                 B	                00:14:47
1	                 C	                00:13:09

0 likes
6 replies
eventter's avatar

We have to deal with start time, formatting issues, lots of calculations, and more. A package called Carbon can help make dealing with date/time in PHP to a very useful package that makes it a breeze to deal with times in PHP. For instance, when creating a trial period for a user, you will want the trial. https://www.mycardstatement.us/

Apostlether's avatar

I came across this older discussion and wanted to add something quick: you can loop through each lesson’s duration, turn it into a Carbon interval, then add them up using CarbonInterval::add. In the end, use totalHours or totalMinutes on the final interval. Curious if anyone has tried storing durations as seconds instead to make summing even easier.

Dewaxdi's avatar

You can just loop through each lesson, convert its duration to seconds with Carbon, and keep a running total, then format it back to hours and minutes. I sometimes sanity‑check my sums with a https://www.gigacalculator.com/calculators/time-calculator.php, since it’s handy for quick adds. Something like Carbon::parse($duration)->diffInSeconds(Carbon::today()) works, then add everything and format with gmdate.

Please or to participate in this conversation.