Calculating Relative Time in PHP

class calculateTime
{
public static function createTimeString($timeStamp, $format=”long”, $dateFormat=”n/j/Y”)
{
// Take the current time and create the difference
$timeDifference = time() – $timeStamp;

// Check the length of time passed since seconds
switch($timeDifference)
{
// Date is less than an hour old
case $timeDifference <= 3600:
$minutes = floor($timeDifference / 60);
$seconds = $timeDifference – ($minutes * 60);

// Choose correct pluralizations
if($minutes == 1)
{
$minuteString = “minute”;
}
else
{
$minuteString = “minutes”;
}

if($seconds == 1)
{
$secondString = “second”;
}
else
{
$secondString = “seconds”;
}

switch($format)
{
case “short”:
return $minutes . “m ” . $seconds . “s ago”;
break;

default:
return $minutes . ” ” . $minuteString . ” ” . $seconds . ” ” . $secondString . ” ago”;
break;
}
break;

// Date is less than a day old
case $timeDifference <= 86400:
$hours = floor($timeDifference / 60 / 60);
$minutes = floor(($timeDifference – ($hours * 60 * 60)) / 60);

// Choose correct pluralizations
if($hours == 1)
{
$hourString = “hour”;
}
else
{
$hourString = “hours”;
}

if($minutes == 1)
{
$minuteString = “minute”;
}
else
{
$minuteString = “minutes”;
}

switch($format)
{
case “short”:
return $hours . “h ” . $minutes . “m ago”;
break;

default:
return $hours . ” ” . $hourString . ” ” . $minutes . ” ” . $minuteString . ” ago”;
break;
}
break;

// Date is less than a week old.
case $timeDifference <= 604800:
$days = floor($timeDifference / 86400);
$hours = floor(($timeDifference – ($days * 86400)) / 60 / 60);

// Choose correct pluralizations
if($days == 1)
{
$dayString = “day”;
}
else
{
$dayString = “days”;
}

if($hours == 1)
{
$hourString = “hour”;
}
else
{
$hourString = “hours”;
}

switch($format)
{
case “short”:
return $days . “d ” . $hours . “h ago”;
break;

default:
return $days . ” ” . $dayString . ” ” . $hours . ” ” . $hourString . ” ago”;
break;
}
break;

// Older than one week. Just return the absolute date.
default:
return date($dateFormat, $timeStamp);
break;
}
}
}

?>

Leave a Reply

Your email address will not be published. Required fields are marked *