Skip to content

Instantly share code, notes, and snippets.

@syammohanmp
Last active October 28, 2022 12:03
Show Gist options
  • Save syammohanmp/fafd8b08b6a92ce8435f89c4d230e8d4 to your computer and use it in GitHub Desktop.
Save syammohanmp/fafd8b08b6a92ce8435f89c4d230e8d4 to your computer and use it in GitHub Desktop.
Get Time ago format.
<?php
/**
* Get Time ago format.
*/
function timeDiff($datetime) {
$time = time() - strtotime($datetime);
$units = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second',
];
foreach ($units as $unit => $val) {
if ($time < $unit) {
continue;
}
$numberOfUnits = floor($time / $unit);
return ($val == 'second') ? 'a few seconds ago' :
(($numberOfUnits > 1) ? $numberOfUnits : 'a')
. ' ' . $val . (($numberOfUnits > 1) ? 's' : '') . ' ago';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment