pee2pee
pee2pee

Reputation: 3792

PHP: Output seconds in H:M value

I have the following code:

echo $diff . ' / ';
echo gmdate("H:i:s", $diff);

This produces

129600 / 12:00:00

However 129600 is 36 hours and not 12, so how could I amend the code to be total hours (36) rather than being 1 day and 12 hours as I don't need to show the day

So if it was 36 hours and 1 minute, I'd want to show: 36:01 or 36:1

Thanks

Upvotes: 0

Views: 82

Answers (3)

Jayesh
Jayesh

Reputation: 161

As of your comment : This doesn't work if it's 08-05-2019 12:00 AM and 09-05-2019 12:00 PM - it brings back 60.
Try following code

$sstartdate = new DateTime('08-05-2019 12:00:00 AM');
$edatetime = new DateTime('09-05-2019 12:00:00 PM');
$since_start = $sstartdate->diff($edatetime);

$hours = ($since_start->days * 24)+($since_start->h);
$min = $since_start->i;
$sec = $since_start->s;

echo $hours.':'.$min;

Output: 36:00
36 hours and 00 minute

Upvotes: 1

Okeyy
Okeyy

Reputation: 58

$hours = floor($diff/ 3600);
$minutes = floor(($diff/ 60) % 60);
$seconds = $diff% 60;

$diff= $hours . ":" . $minutes . ":" . $seconds ;

echo $diff ;

Try this. This may give you the desired result.

Upvotes: 1

Qirel
Qirel

Reputation: 26450

Fetch the days, multiply it by 24 - then add the hours to that, and append the minutes and seconds.

Note that if you have more than 30/31 days, this will stop working again and you will need to account for months or possibly years as well.

$days = gmdate("d", $diff);
$hours = gmdate("H", $diff);
echo ($days*24 + $hours).gmdate(":i:s", $diff);

You can instead go the other way around - extract the seconds and minutes!

$seconds = str_pad($diff % 60, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($diff/60 % 60, 2, '0', STR_PAD_LEFT);
$hours = str_pad($diff/3600, 2, '0', STR_PAD_LEFT);
echo "$hours:$minutes:$seconds";

Upvotes: 1

Related Questions