getTimeDifference function
Copy Below Code
View As A Text File
Show Text Only
Show API
Edit Code
function getTimeDifference($timestamp) {
$currentTime = time();
$timeDifference = $currentTime - $timestamp;
$seconds = $timeDifference;
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$days = floor($hours / 24);
$weeks = floor($days / 7);
$months = floor($days / 30);
$years = floor($days / 365);
if ($years > 0) {
return $years . " year" . ($years > 1 ? "s" : "") . " ago";
} elseif ($months > 0) {
return $months . " month" . ($months > 1 ? "s" : "") . " ago";
} elseif ($weeks > 0) {
return $weeks . " week" . ($weeks > 1 ? "s" : "") . " ago";
} elseif ($days > 0) {
return $days . " day" . ($days > 1 ? "s" : "") . " ago";
} elseif ($hours > 0) {
return $hours . " hour" . ($hours > 1 ? "s" : "") . " ago";
} elseif ($minutes > 0) {
return $minutes . " minute" . ($minutes > 1 ? "s" : "") . " ago";
} else {
return $seconds . " second" . ($seconds > 1 ? "s" : "") . " ago";
}
}
// Usage example
$timestamp = strtotime("2 hours ago");
echo getTimeDifference($timestamp);