Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

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

I just loop through the lessons, parse each duration with CarbonInterval, then add them together. Something like: total = CarbonInterval::seconds($lessons->sum('duration_in_seconds'))->cascade();

Please or to participate in this conversation.