Home >Backend Development >PHP Tutorial >PHP implements relative time function_PHP tutorial
The example in this article describes the PHP implementation of the relative time function. Share it with everyone for your reference. The specific implementation method is as follows:
ใ?
2 3 11 12
<๐>13<๐>
<๐>14<๐>
<๐>15<๐>
<๐>16<๐>
<๐>17<๐>
<๐>18<๐>
<๐>19<๐>
<๐>20<๐>
<๐>21<๐>
<๐>22<๐>
<๐>23<๐>
|
<๐> <๐> <๐>function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {<๐> <๐>if (empty($time) || (!is_string($time) & amp; & amp;<๐> <๐>!is_numeric($time))) $time = time();<๐> <๐>elseif (is_string($time)) $time = strtotime($time);<๐> <๐>$now = time();<๐> <๐>$relative = '';<๐> <๐>if ($time === $now) $relative = 'now';<๐> <๐>elseif ($time > $now) $relative = 'in the future'; else { $diff = $now - $time; if ($diff >= $limit) $relative = date($format, $time); elseif ($diff < 60) { $relative = 'less than one minute ago'; } elseif (($minutes = ceil($diff / 60)) < 60) { $relative = $minutes . ' minute' . (((int)$minutes === 1) ? '' : 's') . ' ago'; } else { $hours = ceil($diff / 3600); $relative = 'about ' . $hours . ' hour' . (((int)$hours === 1) ? '' : 's') . ' ago'; } } return $relative; } |