Calculating Relative Time Stamps With PHP and WordPress

If you go to a social networking site like Twitter, you’ll note that status updates don’t have conventional timestamps on them. Instead of something overly informative (in most cases) like “Posted 2010/07/06 7:50 PM” they tend to show the much more human-friendly “Posted 2 days ago” format for recent dates. These relative time stamps are useful in many cases because of how people think about time. If someone tells you that a new book is going to be released on some date. You immediately think “that’s 3 weeks from today.” Relative time stamps take that extra step out.

Now what do you need to do to display relative time stamps? It’s very simple in WordPress, using the human_time_diff() function. Things are a little bit harder for other projects, where you don’t have the luxury of using the pre-existing WordPress functions.

PHP Snippets has a copy-and-paste-able function that works in much the same way. It takes a UNIX timestamp as an input and uses the “granularity” option you set to find the difference between the times, then returns a string.