Reputation: 67
<?php
function convertToHoursMins($total, $format = '%02d:%02d') {
$hours = intval($total / 60);
$minutes = ($total % 60);
return sprintf($format, $hours, $minutes);
}
echo convertToHoursMins($total, $format = '%02d:%02d');
?>
This solution works perfect (like many other solutions) when $total is positive. When $total on the other hand is negative both $hours and $minutes gets negative like -hours:-minutes. Every solution I have tried echoes the same output, and I am getting frustrated. I really wood appreciate some help!
Upvotes: 1
Views: 112
Reputation: 54841
One of solutions is to work with absolute value of $total
and prepend -
if required:
function convertToHoursMins($total, $format = '%02d:%02d')
{
$absTotal = abs($total);
$hours = intval($absTotal / 60);
$minutes = ($absTotal % 60);
return sprintf((0 <= $total ? '' : '-') . $format, $hours, $minutes);
}
Upvotes: 1
Reputation: 639
function convertToHoursMins($total, $format = '%02d:%02d') {
$total = abs($total);
$hours = intval($total / 60);
$minutes = ($total % 60);
return sprintf($format, $hours, $minutes);
}
Upvotes: 0