Skip to content

Instantly share code, notes, and snippets.

@kyriakos
Created September 2, 2016 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyriakos/315b135c085b4b6a80d4f76ef218b687 to your computer and use it in GitHub Desktop.
Save kyriakos/315b135c085b4b6a80d4f76ef218b687 to your computer and use it in GitHub Desktop.
Convert ps etime to seconds in PHP - [[dd-]hh:]mm:ss
/* coverts process durations output from the ps linux command in the [[dd-]hh:]mm:ss format to seconds
* useful when you need to find long running processes in PHP
*/
function posixTimeToSeconds($str) {
$parts = explode(':', $str);
$c = count($parts);
if ($c == 2) {
return (int)$parts[0] * 60 + (int)$parts[1];
} else if ($c == 3) {
if (strpos($parts[0], '-') !== false) {
$daysHours = explode('-', $parts[0]);
$parts[0] = $daysHours[0] * 24 + $daysHours[1];
}
return (int)$parts[0] * 3600 + +(int)$parts[1] * 60 + (int)$parts[2];
} else {
return 0;
}
}
// Tests
$input = ['21-01:74:01', '3-00:34:41', '00:00', '01:01', '10:10:10', 'test'];
$output = [
(21 * 24 + 1) * 3600 + 74 * 60 + 1,
3 * 24 * 3600 + 34 * 60 + 41,
0,
61,
10 * 3600 + 10 * 60 + 10,
0
];
for ($i = 0; $i < count($input); $i++) {
if (posixTimeToSeconds($input[$i]) == $output[$i]) {
echo 'Test OK ';
} else {
echo 'Test Failed ';
}
echo '(' . $input[$i] . ')' . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment