Page 1 of 1

seconds to min/sec

Posted: Fri Jan 28, 2011 10:47 am
by IGGt
Hi Guys,

I have the following piece of code:

Code: Select all

$ConfRes = mysql_query($query['query1']) ;
        		if ( !$ConfRes ) { 	$error = mysql_error();
	      			print "<table><tr><th>ERROR HAS OCCURRED</th></tr>\"";
        			print "<tr><td>".$error."</td></tr></table>";
    					}              
                while($ConfRow = mysql_fetch_assoc($ConfRes)) {
	                $config = $ConfRow;
	                $sendEmail = $ConfRow['sendEmail'];
	                $emailAddress = $ConfRow['emailAddress'];
	                $pageRefresh = $ConfRow['pageRefresh'];
	                $vUpdate = $ConfRow['vUpdate'];
	                $vAlert = $ConfRow['vAlert'];
	                $vAlarm = $ConfRow['vAlarm'];
	                $esDelays = $ConfRow['esDelays'];
	                $esAlert = $ConfRow['esAlert'];
	                $esAlarm = $ConfRow['esAlarm'];
	                print $esAlarmM;
	               						}
The fields $esAlert and $esAlarm currently contain a number in seconds (e.g. 90). But I want to save this into minutes and seconds (e.g. 1:30), so I was looking to do:

Code: Select all

$esAlertM = gmdate("i", $ConfRow['esAlert']);
$esAlertS = gmdate("s", $ConfRow['esAlert']);
$esAlarmM = gmdate("i", $ConfRow['esAlarm']);
$esAlarmS = gmdate("s", $ConfRow['esAlarm']);
But this doesn't seem to work. Is there a better way to achieve this?

Re: seconds to min/sec

Posted: Sat Jan 29, 2011 9:21 am
by endyourif
gmdate requires a full timestamp, not just a number of seconds. You will need to do something like the following:

Code: Select all

// divide seconds by 60 to get minutes, floor it because we don't want partial numbers
$minutes = floor($ConfRow['esAlert'] / 60);
// seconds will be equal to the left over amount
$seconds = $ConfRow['esAlert'] - ($minutes * 60);

echo 'Time: ' . $minutes . ':' . $seconds;

Re: seconds to min/sec

Posted: Mon Jan 31, 2011 7:59 am
by IGGt
Cheers for that, it worked a treat. I also modified it slightlyto give me leading zeroes each time as well.

Code: Select all

$esAlert = $ConfRow['esAlert'];
$esAlertM = sprintf("%02d",(floor($esAlert / 60)));
$esAlertS = sprintf("%02d",($esAlert - ($esAlertM * 60)));

Re: seconds to min/sec

Posted: Mon Jan 31, 2011 8:16 am
by Weirdan
There's a modulo (%) operator for such cases:

Code: Select all

printf('%02d:%02d', floor($seconds / 60), $seconds % 60);