I have a variable $route->flighttime
which echoes numbers in the following format...
0.5
1.2
1.45
How do I convert it to display HH:MM
using echo
?
Note: 0.5
is treated by the CMS as 50 minutes for some reason.
Based on OPs comments about the format of his initial time (where .5 is actually 50 minutes), a solution without any math
$time = floatval($route->flighttime);
echo number_format($time,2,':',null);
First convert the floating point value to hours/minutes:
$hours = floor($route->flighttime);
$minutes = ($route->flighttime - $hours) * 60;
You can either multiply by 100 instead of 60, or use this technique which might be more accurate:
list($hours, $minutes) = explode('.', sprintf('%.2F', $route->flighttime));
Then use printf
(or some similar function such as sprintf
) to format it properly:
printf("%02d:%02d", $hours, $minutes);
I'm assuming 0.5 means half of an hour. Use gmdate
with format G:i
and your time in seconds:
echo gmdate('G:i', round($x * 3600));
gmstrftime("%H:%M", $t * 60 * 60);
... where $t is float in hours. Notice use of gmstrftime instead of strftime, becouse you do not want to play with timezones.
If the current format is hour and minutes separated by a dot, you could use DateTime
:
$time = DateTime::createFromFormat('G.i', '9.15');
echo $time->format('H:i');
However, in this format, 5
in the minutes section would be 5 minutes, not 50 minutes.