Reputation: 3512
I have a seconds to time function and I want to always output minutes and seconds values as two digits. In other words 5
would become 05
. I used sprintf
in the function, but it is not doing anything. The values are still being returned as single digits.
//convert seconds to time
function convertSeconds($seconds)
{
// extract hours
$hours = floor($seconds / (60 * 60));
// extract minutes
$divisor_for_minutes = $seconds % (60 * 60);
$minutes = floor($divisor_for_minutes / 60);
// extract the remaining seconds
$divisor_for_seconds = $divisor_for_minutes % 60;
$seconds = ceil($divisor_for_seconds);
// return the final array
$obj = array(
"h" => (int) $hours,
"m" => (int) sprintf("%02d", $minutes),
"s" => (int) sprintf("%02d", $seconds)
);
return $obj;
}
Upvotes: 1
Views: 1416
Reputation: 12240
The sprintf
function will format a number correctly if you remove the casting to integer:
$obj = array(
"h" => (int) $hours,
"m" => sprintf("%02d", $minutes),
"s" => sprintf("%02d", $seconds)
);
In the decimal representation integer cannot start with a zero (only hexadecimal, octal and binary representations of integers can start with a zero).
Upvotes: 0
Reputation: 13728
it's problem with casting you are casting of sprint()
not variables so try
$obj = array(
"h" => (int)$hours,
"m" => sprintf("%02d", (int)$minutes),
"s" => sprintf("%02d", (int)$seconds)
);
Upvotes: 1