Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

PHP: Convert hour fractions to hour:minutes

Using PHP, how can I convert hours with fractions to hours with minutes?

For example,
echo hourMinutes(4.5); // 4:30
echo hourMinutes(-4.5); // -4:30
echo hourMinutes(1.9); // 1:54
echo hourMinutes(22); // 22:00

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I formatted the hours to days if it exceeds 24 hours:
function hourMinutes($t) {
	return (($t < 0)?"-":"").date((abs($t)>24)?floor(abs($t)/24).":H:i":"G:i", mktime(0,abs($t)*60));
}

echo hourMinutes(4.5)."<br>";
echo hourMinutes(-4.5)."<br>";
echo hourMinutes(1.9)."<br>";
echo hourMinutes(22)."<br>";
echo hourMinutes(124.3)."<br>";
echo hourMinutes(-124.3)."<br>";

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial