I'm working with php and try to convert decimal to time(hh : mm) but it does not work with any code and tested, the original string is from excel eg:
0.625 = 15:00
0.53541666666667 = 12:51
0.40277777777778 = 09:40
I'm working with php and try to convert decimal to time(hh : mm) but it does not work with any code and tested, the original string is from excel eg:
0.625 = 15:00
0.53541666666667 = 12:51
0.40277777777778 = 09:40
I'd generally recommend using the DateTime
class for any date arithmetic, rather than working it out manually. It'll take into account any daylight-savings/etc (although it's not clear from your question whether or not that would be desired).
<?php
/**
* @param float $x Decimal number of hours
* @return string HH:mm
*/
function dec_hours($x) {
$sec = intval($x * (24 * 60 * 60));
$date = new DateTime("today +$sec seconds");
return $date->format('H:i');
}
echo dec_hours(0.625); // 15:00
echo dec_hours(0.53541666666667); // 12:51
echo dec_hours(0.40277777777778); // 09:40
$dec = 0.625;
This is simple. To convert from decimals to hours, make a multiplication with 24.
$hours = $dec * 24;
Now to convert from decimals to hours:mins
use this:
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
echo convertTime($hours);
Source: How to convert a decimal into time, eg. HH:MM:SS
Output: http://ideone.com/Q7lkwX