Jump to content

[SOLVED] Converting Seconds to minutes:seconds


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);
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.