Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active October 7, 2015 15:28
Show Gist options
  • Save craiga/3186287 to your computer and use it in GitHub Desktop.
Save craiga/3186287 to your computer and use it in GitHub Desktop.
formatTime
<?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