I know that I just went from one extreme (HTML Basics) to another (PHP Func­tions), but I had to write this script today for a per­sonal project I’m cur­rently work­ing on. I thought that because it was so hard for me to find some­thing like this via Google (which turned out to be a bust. NOTE TO SELF: don’t ever search for ‘rel­a­tive time func­tions’ unless you want your brain to explode), that I would post it here, and make it read­ily avail­able to any­body who needs/wants it.

Note: that I took an exist­ing func­tion and mod­i­fied it. The orig­i­nal 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
func­tion relative_time($date) {
$diff = time() - str­to­time($date);
if ($diff>0) {
if ($diff<60)
return $diff . ” sec­ond” . 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”, str­to­time($date));
} else {
if ($diff>-60)
return “in ” . -$diff . ” sec­ond” . 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”, str­to­time($date));
}
}