I know that I just went from one extreme (HTML Basics) to another (PHP Functions), but I had to write this script today for a personal project I’m currently working on. I thought that because it was so hard for me to find something like this via Google (which turned out to be a bust. NOTE TO SELF: don’t ever search for ‘relative time functions’ unless you want your brain to explode), that I would post it here, and make it readily available to anybody who needs/wants it.
Note: that I took an existing function and modified it. The original writer of this code was: Jason Tan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | function relative_time($date) { $diff = time() - strtotime($date); if ($diff>0) { if ($diff<60) return $diff . ” second” . plural($diff) . ” ago”; $diff = round($diff/60); if ($diff<60) return $diff . ” minute” . plural($diff) . ” ago”; $diff = round($diff/60); if ($diff<24) return $diff . ” hour” . plural($diff) . ” ago”; $diff = round($diff/24); if ($diff<7) return $diff . ” day” . plural($diff) . ” ago”; $diff = round($diff/7); if ($diff<4) return $diff . ” week” . plural($diff) . ” ago”; return “on ” . date(“F j, Y”, strtotime($date)); } else { if ($diff>-60) return “in ” . -$diff . ” second” . plural($diff); $diff = round($diff/60); if ($diff>-60) return “in ” . -$diff . ” minute” . plural($diff); $diff = round($diff/60); if ($diff>-24) return “in ” . -$diff . ” hour” . plural($diff); $diff = round($diff/24); if ($diff>-7) return “in ” . -$diff . ” day” . plural($diff); $diff = round($diff/7); if ($diff>-4) return “in ” . -$diff . ” week” . plural($diff); return “on ” . date(“F j, Y”, strtotime($date)); } } |