SatanicGeek
SatanicGeek

Reputation: 342

Show ticks in Days, Hours, Minutes and Seconds

I'm trying to show an UpTime in Days, Hours, Minutes, Seconds. Something like 20 days, 4 hours, 9 minutes, 3 seconds

Here is my PHP Code:

// Get uptime with my SNMP class
$iTicks = $oHardwareMonitoring->fGetSystemUpTime();

// Convert Ticks to seconds
$iSecondes = $iTicks / 100;

// Convert seconds to Days, Hours, Minutes, Seconds
$sSecondes = gmdate('s', $iSecondes);
$sMinutes  = ($sSecondes > 60 ? round(($sSecondes / 60), 0) : null);
$sHeures   = ($sMinutes > 60 ? round(($sMinutes / 60), 0) : null);
$sJours    = ($sHeures > 24 ? round(($sHeures / 24), 0) : null);

// Show the result
echo '<b>'.$sInfosUptime.'</b> : '.
($sJours != null ? $sJours.' '.DAY.' ' : null).
($sHeures != null ? $sHeures.' '.HOUR.' ' : null).
($sMinutes != null ? $sMinutes.' '.MINUTE.' ' : null).
$sSecondes.' '.SECONDE;

When I execute the PHP, I get 38 Seconde(s) for 429859 ticks.

How to show the uptime correctly?

Upvotes: 0

Views: 1591

Answers (2)

spenibus
spenibus

Reputation: 4409

$sSecondes can never be greater than 60 because you use gmdate('s', $iSecondes); which returns a value between 00 and 59. Therefore the conditions that follow will never be evaluated as true.

Using the following line:

$sMinutes = ($iSecondes > 60 ? round(($iSecondes / 60), 0) : null);

returns:

1 HOUR 72 MINUTE 38 SECONDE

Better but not exactly what is expected.

We can get the proper amount of each unit by using modulo, division and floor():

$sSecondes = $iSecondes%60;
$sMinutes  = floor($iSecondes%3600/60);
$sHeures   = floor($iSecondes%86400/3600);
$sJours    = floor($iSecondes/86400);

Which returns:

1 HOUR 11 MINUTE 38 SECONDE

Upvotes: 2

Jordumus
Jordumus

Reputation: 2783

Out the top of my head - wasn't able to check the code as I don't have a webserver available immediately:

// Get uptime with my SNMP class
$iTicks = $oHardwareMonitoring->fGetSystemUpTime();

// Convert Ticks to secondes
$iSecondes = $iTicks / 100;

// Convert secondes to Days, Hours, Minutes, Secondes
$sSecondes = $iSecondes % 60;
$sMinutes = round($iSecondes / 60,0);
$sHeures = round($sMinutes / 60,0);
$sJours = round($sHeures / 24,0);



// Show the result
echo '<b>'.$sInfosUptime.'</b> : '.
($sJours != 0 ? $sJours.' '.DAY.' ' : null).
($sHeures != 0 ? $sHeures.' '.HOUR.' ' : null).
($sMinutes != 0 ? $sMinutes.' '.MINUTE.' ' : null).
$sSecondes.' '.SECONDE;

Upvotes: 0

Related Questions