0

Currently I use the following javascript function to conver seconds to minutes and seconds.

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}

If I pass it 235 it returns 3:55

I've tried to convert it to php, but passing 235 to it I get 55

What have I done wrong ?

function fmtMSS($s){
        return($s-($s%=60))/60+(9<$s?':':':0')+$s;
    };
    echo fmtMSS(235);

Thanks.

mega6382
  • 9,211
  • 17
  • 48
  • 69
Tom
  • 1,436
  • 24
  • 50

3 Answers3

1

You have wrong logic part in your PHP version. Take a look at this:

function fmtMSS($s){
    return(($s-($s%60))/60).(9<$s?':':':0').$s%60;
};
echo fmtMSS(235);

Sandbox: http://sandbox.onlinephpfunctions.com/code/163b767d435cf9db9058d03e95b873fb07e3fcbd

Max Maximilian
  • 591
  • 2
  • 20
1

There is no reason to do it in a one-liner unless its the easiest and most readable way. Don't sacrifice readable code for shorter code.

The below function is the simplest and easiest way to convert seconds into a minute:seconds format. The reason for not using date("H:i", $s) (which would yield the same result) is that it will not scale well, and return incorrect results if $s ever gets high.

Divide by 60, floor it - that will get you the minutes. Multiply it by 60 and subtract it from $s, and you have your seconds.

function fmtMSS($s){
    $minutes = floor($s/60); 
    $seconds = $s-$minutes*60; 
    return "$minutes:$seconds";
};
echo fmtMSS(235); // 3:55

Live demo

The reason your original code doesn't work, is because you're using + to join strings (as you would in JavaScript). However, in PHP, one uses . to contact two strings. The logic also seems to be a bit incorrect.

Qirel
  • 25,449
  • 7
  • 45
  • 62
0
<?php 
function fmtMSS($s){
    $min = floor($s/60);        
    $sec = $s%60;
    return $min.':'.$sec;
};
echo fmtMSS(235);
?>

Use this code- i have just edited your function.

for short:- echo gmdate("i:s", 235);

Ajit Maurya
  • 56
  • 1
  • 9