Let PHP's powerful array of date-related features ease the often ugly task of date formatting and manipulation.
No matter what sort of web site you're building, chances are that a fair amount of the code you write will be involved in the formatting, manipulation, and calculation of times and dates. This is because temporal data plays an important role in so many aspects of business and life. So, as a developer you'll need to be well versed in creating features that perform tasks such as telling the user how many days have passed since he last logged in, including the customer's product purchase date on an invoice, and retrieving a list of articles published to your web site within the past 30 days.
The PHP language has long sported powerful date formatting and manipulation capabilities, greatly reducing the amount of work the developer has to do in this regard. In this tutorial, I'll introduce you to some of PHP's more commonly used date-manipulation features, and offer a few lesser-known tips and tricks along the way.
Displaying the Date
PHP's date() function is so impressive that many tutorials and books (including my own "Beginning PHP and MySQL") often use the function within an introductory example as a way to acquaint the user with the language's simple yet powerful syntax. This function's dizzying array of options make it possible to format a date and time in practically every conceivable manner (even Swatch Internet Time if you so desire). For instance, to display the current date in a format that won't cause confusion otherwise brought on by country-specific ordering standards, you can use the option sequence F j, Y:
echo date("F j, Y");
Executing this snippet will produce a date that looks like this:
January 2, 2010
If your users are all based in the United States, then using the option sequence m-d-y will probably suffice:
echo date("m-d-y");
// outputs 01-02-10
The format syntax demonstrated here is just a small part of what the date() function can do. Be sure to check out the function's documentation for all the details.
Formatting a Timestamp
The date() function accepts an optional parameter representing a timestamp. A timestamp is simply a representation of a specific date and time, and although timestamps can be represented using a variety of syntax formats, the date()
function expects it to be provided as a sequence of integers representing the number of seconds that have passed since the Unix Epoch. It's common practice to use timestamps of this nature, and so if you have one handy, you can use the date() function to convert it to a more user-friendly format. For instance:
$tstamp = "1032554992"; echo "The timestamp {$tstamp} represents the date/time: ". date("m-d-Y h:i:s", $tstamp);
Executing this snippet produces the following output:
The timestamp 1032554992 represents the date/time: 09-20-2002 04:49:52
Localizing the Date
Of course, not all of your users are likely to be native English speakers. So, you might consider greeting users with a format more familiar to their native languages, which is easy to do using PHP's setlocale() and strftime() functions. For instance, if a particular user has identified himself as a citizen of France, you could localize PHP's date-specific syntax using the fr_FR locale, and then format the date using some of the strftime() function's options:
Executing this snippet produces the following output:
02 janvier, 2010
Depending upon how your server is configured, it may not support every available locale. The easiest way to determine whether one is supported is to check the return value of your setlocale() call. If it returns FALSE, the locale is not supported:
Web servers often reside in a time zone completely different from the business they serve. For instance, my consulting and publishing business resides in Columbus, Ohio (Eastern Standard Time), but the web site is hosted on a server residing in southern California. Because PHP will by default report times and dates based on the server's time zone configuration, if you are in a situation similar to mine, you should override these settings and adjust the time zone accordingly. If you want all PHP scripts residing on the server to use a specific time zone, open the php.ini file and locate the date.timezone directive. You can set this directive to any of PHP's
supported time zones (you can find a list of available settings here). For instance, to set the Eastern time zone I could use the America/New_York setting:
date.timezone = 'America/New_York'
If you wanted only a specific PHP script to use a specific time zone, you can use the date_default_timezone_set() function at the top of your script:
date_default_timezone_set('America/New_York');
Performing Date Calculations
Outputting formatted dates is easy enough, but what if you wanted to calculate the date 60 days from today, or figure out how many days separate two different dates? Although these are commonplace problems, devising your own solutions for such tasks is a difficult and error-prone process. The new DateTime class features available as of PHP 5.2 effectively remove the need for you to create custom date calculation solutions. In the following section, I present two examples that demonstrate the power of this class.
Adding 45 Days to a Date
Suppose you were tasked with creating a video download service, which gave the subscriber 60 days from the time of payment to download a particular video. Because of the varying number of days associated with each month, coupled with the additional complexity of leap years, accurately communicating the expiration date to the customer could be difficult. Using the DateTime class, such a calculation is easy:
date_default_timezone_set('America/New_York');
$startDate = new DateTime('2010-01-02 00:00:00');
date_add($startDate, new DateInterval("P60D");
echo "<p>Your video download will expire on ".$startDate->format("m-d-Y")."</p>";
Executing this code produces the following output:
Your video download will expire on 04-02-2010.
The DateInterval format syntax certainly looks odd at first; the P stands for period. Following that, you can use other period designators that represent much more than just days. For instance, to determine the date falling 2 years and 47 days after a specified date, you can use the format P2Y47D. See the DateInterval documentation for more details.
Calculating the Number of Days Separating Two Dates
The Ohio State Buckeyes football team has as of late had the upper hand on their archrival Michigan Wolverines, having not lost a game to the northern foe since November 22, 2003. Suppose you created an OSU Buckeye fan site and wanted to greet visitors with a running count of the number of days that have passed since this last loss to Michigan? Using the DateTime class's diff method (available as of PHP 5.3.1), the task is easy:
date_default_timezone_set('America/New_York');
$loss = new DateTime('2003-11-22 00:00:00');
$days = $loss->diff(new DateTime('2010-01-02 00:00:00'));
echo "<p>".number_format($days->days)." days have passed since OSU's last loss to Michigan!</p>";
Executing this code on January 2, 2010 produces the following output:
2,233 days have passed since OSU's last loss to Michigan!
Where to From Here?
This tutorial introduces a mere fraction of PHP's available date and time functions. For a complete list, be sure to check out this list of date/time functions, located in the PHP manual.
Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.