Last active
October 7, 2015 15:28
-
-
Save craiga/3186287 to your computer and use it in GitHub Desktop.
formatTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Format a number of seconds. | |
* | |
* Format a number of seconds into a number of seconds, minutes, hours and days. | |
* Produces output like "1 second", "110 seconds", "4 hours" or "123 microseconds". | |
* The accuracy gets a little rough once it gets into months, but it's only meant | |
* as an approximation. | |
* | |
* @author Craig Anderson <[email protected]> | |
* @link https://gist.github.com/3186287 | |
*/ | |
function formatTime($time) | |
{ | |
$unit = "seconds"; | |
if($time < 1) | |
{ | |
$time = $time * 1000; // seconds to milliseconds | |
$unit = "milliseconds"; | |
if($time < 1) | |
{ | |
$time = $time * 1000; // milliseconds to microseconds | |
$unit = "microseconds"; | |
} | |
if($time < 1) | |
{ | |
$time = $time * 1000; // microseconds to nanoseconds | |
$unit = "nanoseconds"; | |
} | |
} | |
else | |
{ | |
if($time > 120) | |
{ | |
$time = $time / 60; // seconds to minutes | |
$unit = "minutes"; | |
} | |
if($time > 120) | |
{ | |
$time = $time / 60; // minutes to hours | |
$unit = "hours"; | |
} | |
if($time > 48 && $unit == "hours") | |
{ | |
$time = $time / 24; // hours to days | |
$unit = "days"; | |
} | |
if($time > 60 && $unit == "days") | |
{ | |
$time = $time / 30; // days to months | |
$unit = "months"; | |
} | |
if($time > 24 && $unit == "months") | |
{ | |
$time = $time / 12; // months to years | |
$unit = "years"; | |
} | |
} | |
if($time == 1) | |
{ | |
$unit = preg_replace("/s$/", "", $unit); // remove "s" from end of unit | |
} | |
return sprintf("%s %s", number_format($time), $unit); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment