function time_ago(string $datetime, DateTime $now = null, bool $full = false, string $format = null): string
{
try {
$ago = new DateTime($datetime);
if ($now === null) {
$now = new DateTime();
}
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) {
$string = array_slice($string, 0, 1);
}
if ($format === 'detailed') {
return $string ? implode(', ', $string) . ' ago' : 'just now';
} else {
return $string ? implode(' ', $string) . ' ago' : 'just now';
}
} catch (Exception $e) {
// handle exception
}
}
// Get the current time
$now = new DateTime();
// Calculate the difference between the current time and a past date, with the default format
echo time_ago('2022-01-01'); // Outputs something like "1 year, 3 months ago"
// Calculate the difference between two past dates, with the detailed format
echo time_ago('2020-01-01', '2021-01-01', true, 'detailed'); // Outputs something like "1 year, 3 months, 2 weeks, 5 days ago"
// Calculate the difference between a past date and the current time in a different timezone
$tz = new DateTimeZone('Asia/Tokyo');
$ago = new DateTime('2022-01-01', $tz);
echo time_ago($ago, $now, false, 'detailed'); // Outputs something like "1 year, 3 months ago"