Working with Dates
In the very first example in this tutorial, we slipped in a sneaker without explanation - a reference to the insanely useful PHP
date() function. It's very common for sites (especially news sites) to render the current date in the masthead or elsewhere. It's also often necessary to take timestamps stored in a database and render them in various formats -- in the dateline of a story, for example.
date() function gives you great flexibility in how dates should be rendered, letting you work in formats either strict or user-friendly, in normal time or military time, with or without abbreviations. In fact, one of the most visited pages on the php.net site is the date function's official reference. You'll see a ton of optional arguments on that page, but don't worry - you usually only need a few of them. The
date() function works like this:
What's that "l" doing there? Take a look in the function reference and you'll see that "l" is substituted with "A full textual representation of the day of the week." So it's going to display whatever the current day of the week is. You can string the "variables" in the date argument together however you like, with punctuation mixed in as needed. Let's say you wanted to display:
Monday 8th of August 2005 03:12:46 PM
You'd use the following string of variables in the argument to
Look each of these variables up in the function reference to see what role they play.
That's all well and good for rendering the current date and time, but what if you want to customize the output of a date in the past, such as the dateline for a news article? In that case, simply hand the
date() function the date you want handled as a second argument in a valid timestamp format (such as a timestamp emitted from your database), like this: