This is old content! The graveyard is a snapshot of content created from 2002-2005. For new stuff, visit Maniacal Rage.
 

Relative Dates Using PHP

posted on february 26, 2004, tag: movable type

So you want to jump on the relative dates bandwagon? Here's how you can do it quickly and easily. This tutorial will assume you're using Movable Type, but you can use the PHP bit on its own if you wish*. You could also do this via SQL, but in this case it's easier to use a function than to edit how MT queries the DB. First, let's talk about the PHP function.

The idea here is simple: You pass the function a date stamp in a specific format (YYYYMMDDHHMMSS) and it converts that stamp into a Unix timestamp (in seconds since the Epoch). It then finds the difference between the current time and that timestamp. This number is the number used to calculate the relative values. It works as such:

  • A minute contains 60 seconds.
  • An hour contains 60 minutes (3600 seconds).
  • A day contains 24 hours (86400 seconds).
  • A week contains 7 days (604800 seconds).
  • A month contains 30 days (2592000 seconds).
    Obviously, not all months contain 30 days. This is an average and will provide results that are reliable enough in this case.

The function works from the largest timeframe down. If the amount of months is 1 or greater, then the function will simply return the date in MM/DD/YYYY format. The reason for this is that you don't want someone looking your archive from a year ago and seeing a posted date of 1 year, 3 months ago. How would they know when exactly that was? If a month has not gone by, the function moves down to weeks. The way the function builds results is as follows:

  • If there are 1 or more months, return just a date.
  •      Otherwise:
  • If there are 1 or more weeks, return weeks and, if necessary, days.
  •      Otherwise:
  • If there are 1 or more days, return days and, if necessary, hours.
  •      Otherwise:
  • If there are 1 or more hours, return hours and, if necessary, minutes.
  •      Otherwise:
  • If there are 1 or more minutes, return minutes.
  •      Otherwise:
  • Just return seconds.

This means you'll never see something like 4 weeks, 3 days, 8 hours, 32 minutes, 11 seconds returned. That's just crazy. This limits each set of time to one (or no) subset. Now then, let's put it all together.

First, click here to see and copy the source code for the PHP function. Copy that code and put it into your functions file (or, if you're completely unorganized, create a new file) and make sure you include it on all the templates you wish to use these dates on (like such: <?php include('functions.php'); ?>, where functions.php is the file that contains the function). Then, where's you want the date to appear, do this:

Posted <?=doRelativeDate('<$MTEntryDate format="%Y%m%d%H%M%S"$>');?>

Note that the function automatically adds the text ' on' when it prints only a date and ' ago' when it prints a relative date. Hence my addition of the word 'Posted' and the space after it in the code above. The function doesn't automatically print the 'Posted' part because some people might want it to say 'Written' or 'Barfed' or something. Rebuild and you've got yourself some relative dates, pal.

* If you want to use this without Movable Type, you can simply substitute what I passed to the function above with your own properly formatted date stamp (see mktime(), date(), etcetera).

Comments

There are 9 comments, comments are closed

David Collantes on 02/26/2004:

Excellent! Thanks a lot Garrett! I am clicking on one or two of your Google Ads, as a way to say "thank you" :-)

Cheers!

Mark Nichols on 02/27/2004:

Very nice! I have wanted to display dates in this fashion for some time now and you've saved me the effort of discovering how.

Thanks!

Max on 05/30/2004:

Nice work, Garrett. Thanks for making it available for all.

I just noticed the link you have to the source file on this page is incorrect though.

Michael on 09/25/2004:

Diggin' it... but...

My limited knowledge correct of PHP syntax is killing me. With Wordpress, I'm trying:


<?=doRelativeDate(the_date());?>

But it outputs something along the lines of:

20040925163619on //

Any thoughts?

arthaus on 11/09/2004:

Thankx Garrett!

I appreciate your generosity. I implemented your code at my auction ledger.
http://www.goodtidings.org/site/?home
http://www.goodtidings.org/auction_04/ledger.php

Sincerely, Arthur

Tom on 06/22/2005:

Very nice! Thanks!
Just thought though to point out that assuming there are 30 days in each month I get (30*24*60*60) = 2592000 and not 2419200.
That leaves a two day difference (48 hours) - given calculation of seconds turns into years it will start to make a significant difference (1 year = 24 days less).
I'm assuming this was done in purpose - could you elaborate?
:-)

Garrett on 06/23/2005:

Tom—actually, that's just a really bad math error on my part. A math error that has been in the code this whole time. You're the first person to notice it.

I've fixed the code in the entry and the linked source, as well as in my current function that's been running on the site for nearly 2 years with that error.

Thanks!

codehelp on 06/30/2005:

I want to display the date in a textbox using js, but it is not allowing me to display it. I can display the time but not the date. Pls help. Can you send the code using php to display the date in textbox

Adrian on 07/10/2005:

Great function, but theres no need to restrict it to past dates. I've made some modifications so that future dates can be given.

Replace:

$diff = time()-$in_seconds;

with


if(($diff = time()-$in_seconds) < 0) {
        $diff = abs($diff);
        $posted_date_is_future = true;
    }
    else
        $posted_date_is_future = false;

and replace:

return $relative_date.' ago';

with

return $posted<em>date</em>is<em>future ? \"{$relative</em>date} away\" : \"{$relative_date} ago\";


See Also

View the archive

Original iPod Introduction
How far we've come in just a few short years. Here's where it all started.

Front Row on Non-iMacs
Going to try this tonight!

WriAShorStorWe!
DY starts a one-week short story writing event for people to lazy to enty NaNoWriMo. VerCooIdea.

Lost Rhapsody
Funny Flash movie using Weird Al music and Lost stuff. Lyrics make a surprising amount of sense!

Jed's Other Poem
Unsolicited music video made on an Apple ][. Fantastic!

Printers Output Secret Barcode
The government is keeping tabs on what you print, with the help of major printer companies.

Dreamhost Promo Codes
DH already has very cheap, very good hosting—this just sweetens the deal.

Photos of the new iPod
Just received my new iPod and I put a few photos up.

PEZ MP3 Player
Funny idea that actually looks kind of neat. I like that it comes pre-loaded with "indie" music.

HD Easter Egg
"My Name is Earl" on NBC gives viewers with HD TVs a little easter egg. Cute, but weird.