Here’s a lightweight PHP function which accepts a date as a parameter and converts it into “sometime age” output.ime_ao($date) {
if (empty($date)) { return "Please enter a date!"; } $duration_in = [ "second", "minute", "hour", "day", "week", "month", "year", "decade" ]; $len = [ "60", "60", "24", "7", "4.35", "12", "10" ]; $now = time(); $unixDate = strtotime($date); if (empty($unixDate)) { return "Please enter a valid date!"; } if ($now > $unixDate) { $diff = $now - $unixDate; $tense = "ago"; } else { $diff = $unixDate - $now; $tense = "from now"; } for ($j = 0; $diff >= $len[$j] && $j < count($len) - 1; $j++) { $difference /= $len[$j]; } $diff = round($diff); if ($diff != 1) { $duration_in[$j].= "s"; } return "$diff $duration_in[$j] {$tense}"; }
Usage:
echo time_ago($date);
0 comments:
Post a Comment