Converting Timestamps to "Time Ago" in PHP
You are dealing with a fundamental mismatch between date formats. The string 2009-09-12 20:57:19 is a human-readable datetime, whereas the snippet you found expects an integer representing Unix time (the number of seconds since January 1, 1970).
The error in your logic stems from attempting to subtract a string directly from an integer. In PHP, while loose typing allows some arithmetic with strings, subtracting a formatted date string like 2009-09-12 20:57:19 from time() will not yield the precise difference in seconds required for the _ago function to calculate intervals correctly. You need to normalize that input string into an integer timestamp first.
The standard approach is to use strtotime(). This built-in function parses a date/time string and returns a Unix timestamp.
$inputString = '2009-09-12 20:57:19';
$unixTimestamp = strtotime($inputString);
Once $unixTimestamp holds the integer value, you can proceed with the subtraction logic found in your source script. The math becomes: $dif = time() - $unixTimestamp;. This gives you the raw difference in seconds, which is exactly what the array $lngh (containing 1, 60, 3600, etc.) expects for its division operations.
Refactoring the Logic
While your source script works, it relies on a nested function call (time_ago($_tm)) that isn't defined in the snippet you provided, and it lacks error handling if $rcs is passed incorrectly. A more robust implementation usually handles the relative time calculation inline or uses a cleaner loop structure to avoid recursion issues.
Here is a refined version of the logic that accepts your specific datetime string format directly:
function getRelativeTime($datetime) {
$cur_tm = time();
// Convert the input string to a Unix timestamp
$input_ts = strtotime($datetime);
if ($input_ts === false) {
return 'Invalid date';
}
$dif = $cur_tm - $input_ts;
if ($dif >= 0) {
// Logic to determine the largest unit of time that fits within 1 unit
$pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$lngh = array(1, 60, 3600, 86400, 604800, 2592000, 31536000);
for ($v = count($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--);
if ($v < 0) $v = 0;
$_tm = $cur_tm - ($dif % $lngh[$v]);
$no = floor($no);
if ($no !== 1) {
$pds[$v] .= 's';
}
$x = sprintf("%d %s ago", $no, $pds[$v]);
return $x;
} else {
// Handle future dates
return 'in ' . getRelativeTime(abs($dif));
}
}
// Usage
echo getRelativeTime('2009-09-12 20:57:19');
// Output example: "34 years ago" (depending on current system time)
Handling Timezones and Precision
A common pitfall when working with strtotime() is timezone handling. If your application runs on a server in UTC but your user expects the relative time based on their local browser timezone, the calculation might be off by several hours.
If you are using Laravel or a similar framework that manages the database and timezone configuration automatically, ensure you are converting the timestamp to the correct timezone before passing it to strtotime(), or pass a timezone-aware DateTime object if your PHP version supports it (PHP 7.3+).
For example:
$date = new DateTime('2009-09-12 20:57:19', new DateTimeZone('America/New_York'));
$timestamp = $date->getTimestamp();
Modern Alternatives with Carbon
While the algorithmic approach above demonstrates how the math works, modern PHP development often favors dedicated libraries for date manipulation. The Carbon library (or its Laravel integration) abstracts away these manual calculations entirely. It handles timezone offsets, leap years, and human-readable formatting gracefully.
If you are building an application where this feature is critical, consider using Carbon's built-in diffForHumans() method:
use Carbon\Carbon;
$date = Carbon::parse('2009-09-12 20:57:19');
echo $date->diffForHumans();
// Output: "about 14 years ago"
This approach is less error-prone and significantly more readable than implementing the raw math yourself. For simple scripts, the strtotime() method combined with the logic provided above is perfectly sufficient and requires no external dependencies. However, in larger applications, relying on established libraries reduces technical debt and potential edge-case bugs.
