
Chris
Staff

Jan 6, 2011, 5:02 PM
Post #1 of 7
(35846 views)
Shortcut
|
|
Facebook-style relative times (e.g. "7 hours ago")
|
Can't Post
|
|
Hi everyone, I just wrote a bit of code that I thought someone might find useful; it turns a date into a more human-readable format such as "37 seconds ago", "about an hour ago", "Wednesday at 6:07pm", or "February 17, 2007", depending on how far in the past the date is. It doesn't handle future-dates at all.
<?php function pretty_relative_time($time) { if ($time !== intval($time)) { $time = strtotime($time); } $d = time() - $time; if ($time < strtotime(date('Y-m-d 00:00:00')) - 60*60*24*3) { $format = 'F j'; if (date('Y') !== date('Y', $time)) { $format .= ", Y"; } return date($format, $time); } if ($d >= 60*60*24) { $day = 'Yesterday'; if (date('l', time() - 60*60*24) !== date('l', $time)) { $day = date('l', $time); } return $day . " at " . date('g:ia', $time); } if ($d >= 60*60*2) { return intval($d / (60*60)) . " hours ago"; } if ($d >= 60*60) { return "about an hour ago"; } if ($d >= 60*2) { return intval($d / 60) . " minutes ago"; } if ($d >= 60) { return "about a minute ago"; } if ($d >= 2) { return intval($d) . " seconds ago"; } return "a few seconds ago"; } ?> USAGE: <?php echo pretty_relative_time($record['createdDate']); ?> I hope this is helpful to someone! :D Chris
(This post was edited by Damon on Feb 7, 2011, 10:56 AM)
|