Jump to content

[SOLVED] Converting Seconds to minutes:seconds


tbare

Recommended Posts

Well, 197 seconds is actually 3 minutes and 17 seconds. Anyways, try:

 

<?php
function convert($seconds){
$minutes = floor($seconds / 60);
$seconds = round($seconds % 60,2);
return $minutes.':'.$seconds;
}
echo convert(197.733333);
?>

Or if you don't mind using antiquated C style functions:

 

$a = 197.333333;
$minutes = floor($a/60);
printf("%d minutes\n", $minutes);
printf("%.0f seconds\n", $a - ($minutes * 60));

 

printf's rounding will go to the closest number.  You can use sprintf() if you want to store the result in a variable instead.

firstly: thanks for the correction of 3:17 (it had been a long day of programming) :)

 

secondly: GingerRobot's answer worked.... until i had a file that had seconds less than 10...

 

to fix this, all i did was add:

<?php
if($seconds < 10){
$seconds = "0" . $seconds;
}
?>

 

so the total code was:

<?php
$duration = $movie->getDuration();
$minutes = floor($duration / 60);
$seconds = round($duration % 60,2);
if($seconds < 10){
$seconds = "0" . $seconds;
}
$duration = $minutes.':'.$seconds;
?>

 

then just included that file before i printed $duration...

 

Thanks for all the help guys!

Ah yeah, sorry. Didn't think that one through completely. An alternative to the if statement would be the str_pad function:

 

<?php
$duration = $movie->getDuration();
$minutes = floor($duration / 60);
$seconds = round($duration % 60,2);
$duration = $minutes.':'.str_pad($seconds,2,'0',STR_PAD_LEFT);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.