seconds to min/sec

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

seconds to min/sec

Post 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?
endyourif
Forum Newbie
Posts: 7
Joined: Wed Jan 26, 2011 6:53 pm

Re: seconds to min/sec

Post 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;
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: seconds to min/sec

Post 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)));
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: seconds to min/sec

Post by Weirdan »

There's a modulo (%) operator for such cases:

Code: Select all

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