Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon Difference in Time between two Dates in hh:mm:ss format

I'm trying to figure out how I can take two date time strings that are stored in our database and convert it to a difference in time format of hh:mm:ss.

I looked at diffForHumans, but that does give the format I'd like and returns things like after, ago, etc; which is useful, but not for what I'm trying to do.

The duration will never span days, only a max of a couple hours.

$startTime = Carbon::parse($this->start_time); $finishTime = Carbon::parse($this->finish_time);  $totalDuration = $finishTime->diffForHumans($startTime); dd($totalDuration);  // Have: "21 seconds after" // Want: 00:00:21 
like image 422
mtpultz Avatar asked Nov 06 '15 20:11

mtpultz


People also ask

How do I change the date format in carbon?

Carbon::parse($client->db)->format('d/m/y'); is probably what you're wanting. (parse the yyyy-mm-dd date in the database as a date, and convert it to d/m/y format).

How do you find the difference between two times in laravel carbon?

Help of Carbon class we can simply calculate minutes difference between two dates. you can simply customize code also. In Following example you can see, we have a two dates, first $to variable and second one $from variable. Carbon class diffInDays function using you can get difference between two dates.

How do you find the difference between two dates and seconds?

We have the startDate and endDate which we can convert both to timestamps in milliseconds with getTime . Then we subtract the timestamp of endDate by the timestamp of startDate . This will return the timestamp difference in milliseconds. So we divide the difference by 1000 to get the difference in seconds.


2 Answers

I ended up grabbing the total seconds difference using Carbon:

$totalDuration = $finishTime->diffInSeconds($startTime); // 21 

Then used gmdate:

gmdate('H:i:s', $totalDuration); // 00:00:21 

If anyone has a better way I'd be interested. Otherwise this works.

like image 88
mtpultz Avatar answered Oct 05 '22 08:10

mtpultz


$finishTime->diff($startTime)->format('%H:%I:%S'); // 00:00:21 
like image 26
STWilson Avatar answered Oct 05 '22 08:10

STWilson