date() is the first function that developers respond to with “Oh, that’s why I would use PHP!”
Before we get to the function itself, a small reminder: on the whole, HTML and CSS are stateless, which means (among other things) that they have no concept of time. The only way to place today’s date on a webpage using HTML is to physically write it out on the page, mark up the code, and upload it to the server… each and every day.
With PHP, placing the current day of the week on the page couldn’t be easier:
<p>Today is <?php echo date('l'); ?>
(That’s a lowercase L used inside single quotes for the
This piece of code demonstrates several important points:
- PHP is, generally speaking, used for dynamic data, i.e. content that changes. In this example, we always want our paragraph to start with the words “Today is”, so it makes little sense to place those words inside a PHP statement. The only thing that changes is the actual name of the day, so that part is PHP.
echocan be used to print out strings, the value of variables, or the result of functions.
- It is important that there is a space somewhere between “is” and the day of the week, otherwise the text will run together.
date()function works with “switches”: individual letters placed into the function to generate date components.
date() can also be used to generate the time. A complete list of switches can be found at the php.net website entry for
date(), but for now let’s use an example:
<p>It is now <?php echo date('g:i A')." on ".date('l j F, Y'); ?>
Using concatenation, the result is a much more verbose readout of the current day and time : “It is now 3:07 am on Monday 31 December 2014”.
Using date() with includes
date() function can also be used in includes. Oddly, you do not have to change the extension of the include file to do so. (This means that any PHP that you use on the included file won’t be color-coded correctly in programs like Dreamweaver, but that’s not a major issue. You don’t have to change the extension as any PHP in an included file is run after it is called into a PHP page.)
For example, let’s say you have a copyright notice at the bottom of every page of your website. Having thought ahead, you have decided to make this portion of code an include file, with the filename footer.html. In this file is the following code:
<h4>Copyright © 2010 Grievous Genophage Inc.</h4>
Your client is copyright-obsessed, and wants the copyright notice updated every year. Rather than using New Year’s to update the website every time, you can modify footer.html to become:
<h4>Copyright © <?php echo date('Y'); ?> Grievous Genophage Inc.</h4>
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.