twitter facebook dribbble email

Displaying dates the easy way

Careful! This post is looking a little old and could be inaccurate in many, many ways

For many the code I’ll be putting on this post will appear pretty simple and it is. Yet not everyone is well versed in programming or they are just starting out and still learning the small tips and tricks that many of us take for granted. So here’s a little trick to make the dates on your website a bit more dynamic using PHP.

I’m using PHP because it’s still the most widely used server side language and if you get the theory behind the PHP version it’s usually simple enough to transfer that to a different language even if you need a little help from Google.

The static method

Most websites tend to display a date as part of a copyright notice at the base of a website, displaying something along the lines of:

With the date hard coded in this way it usually means a web developer will be changing this code once a year if they wish it to reflect the current date rather than the date of the websites launch.

Being a little more dynamic

By replacing the static date with a PHP function you can save yourself the work of having to manage the date shown yearly:

The Date function is an inbuilt PHP function which means it does all the work for you, all you need to do is pass it the format in which you wish the date to display. In this case we add ‘Y’ to show the date as a four digit year. For more information about date formats you can use visit the PHP website.

Displaying a date range

Rather than show a single date you may wish to show a date range, in this case usually the year the website launched to the current year. Statically this might look like this:

To make this dynamic you simply change the second date to use the PHP function as shown above:

This still isn’t as useful as it might first appear. Often you can be building a brand new website rather than redesigning a pre-existing website. This means that the launch year and current year will be the same. You could add a single date and swap it for the above code after the first year, safe in the knowledge you’d not have to make any changes the following year but really you should only need to write the code a single time.

So to cover all the bases we write something a little more complex:

What this does is show only a single year if the current year is the same as that you have hand coded into the function. Otherwise it will show the two year range. What this function also allows is for you to be able to add any date be it if the website is brand new or a few years old and it will display exactly what is required.

It’s a simple piece of code but it means you have a function suitable for any website that requires no yearly updates of the date, if that’s something you would usually do.