Ring in the new year with a little PHP

I think this has happened to every web developer at one point or another: You complete and launch a site, revel in it’s glory, January 1st passes you by and suddenly, embarrassingly, the site proudly proclaims the previous year in the footer!

Ack! How’d you miss that? So unprofessional.

Many of you have probably used the following solution to combat this troublesome oversight:

<?php echo date('Y'); ?>

In PHP, this displays the current year. But what if you want to intelligently display a span of time, regardless if your project launched this year or five years ago?

Here’s a fun little function my good friend (and ace developer) Peter Wooley showed me some time ago:

function copyrightYear($start,$between='-',$echo=true) {
    $current = date('Y');
    $result = $current > $start ? $start.$between.$current : $start;
    if ($echo) echo $result;
    return $result;
}

The first attribute ($start) is the launch date of your site, the first year of the date span. $between is what goes between the start and end year (when applicable). If you set $echo to false, the value will be returned instead of echoed.

So if your site debuted in 2009, you would use the following:

<?php copyrightYear(2009); ?>

If the year is 2009, it will echo ‘2009’. In 2010, it will echo ‘2009-2010’.

Now sit back and rest easy next New Year’s Day knowing your footers shan’t go out of date again!

Responses

Jim Goings says

Nice post. I will implement this on my own sites now. :)

BTW – what’s with the “no bacon” next to the mail field? Who doesn’t want bacon? Seriously man.

Responded

Tyler Sticka says

Thank you, sir! I’m referring of course to the oft-forgotten cousin of spam, “bacon.” More commonly, bacn.

Responded

Leave a response

Your email address won’t be published. You can use some HTML or Markdown.