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
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).
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.
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.
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.
$finishTime->diff($startTime)->format('%H:%I:%S'); // 00:00:21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With