Reformat php date compare function
Question
Found the following snippet online and are currently using it in my web application, however it returns time like "0:5:1". I would like it to format the output like a real date, ie: 00:05:01.
Guess that there is an embarrassing quick solution to solve this. Here comes the snippet:
function getTimeDifference($start, $end) {
$uts['start'] = $start;
$uts['end'] = $end;
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return $hours . ':' . $minutes . ':' . $diff;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
return FALSE;
}
Thanks a lot!
Solution
Try sprintf
return sprintf("%02:%02d:%02d", $hours, $minutes, $diff);
OTHER TIPS
You could use str_pad()
to padd the values with a "0".
return str_pad($hours, 2, "0", STR_PAD_LEFT); // turns '5' into '05'
like
echo "Hours: " .sprintf( '%02d:%02d', $diff['hours'], $diff['minutes'] );
i see a similar function in link
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow