You can create a function in PHP to convert a DATETIME into a “time ago” format that displays the elapsed time in seconds, minutes, hours, days, etc. To do this, you can calculate the time difference between the given DATETIME and the current time, and then format the result accordingly. Here’s an example of such a function:
function timeAgo($dateTime) {
$currentTimestamp = time();
$dateTimeTimestamp = strtotime($dateTime);
$timeDifference = $currentTimestamp - $dateTimeTimestamp;
if ($timeDifference < 60) {
return $timeDifference . ' seconds ago';
} elseif ($timeDifference < 3600) {
$minutes = floor($timeDifference / 60);
return $minutes . ' minutes ago';
} elseif ($timeDifference < 86400) {
$hours = floor($timeDifference / 3600);
return $hours . ' hours ago';
} else {
$days = floor($timeDifference / 86400);
return $days . ' days ago';
}
}
// Example usage:
$dateTime = '2023-11-01 12:00:00'; // Your DATETIME
$timeAgo = timeAgo($dateTime);
echo $timeAgo;
In this function:
- We calculate the time difference in seconds between the given
DATETIME
and the current time using thetime()
function andstrtotime()
function. - Depending on the value of the time difference, we format the result to display the time in seconds, minutes, hours, or days.
- We return the formatted "time ago" string.
You can modify the function and the output format to suit your needs. This is a basic example, and you can add more conditions or customize it further as necessary.