Page 526 - Beginning PHP 5.3
P. 526
Part III: Using PHP in Practice
At the time of writing, these classes were relatively experimental and not feature - complete; however,
they are already useful. They provide a number of advantages over the traditional PHP date and time
functions, including:
❑ Elegant handling of time zones
❑ The ability to store and handle dates before 1901 and after 2038
❑ Easier date manipulation
th
For example, the following code creates a new DateTime object representing 13 Feb 1948 in the Los
Angeles time zone, then subtracts three months from the date, displaying the result:
$dtz = new DateTimeZone( “America/Los_Angeles” );
$dt = new DateTime( “13-Feb-1948”, $dtz );
$dt- > modify( “-3 months” );
// Displays “Thu, 13 Nov 1947 00:00:00 -0800”
echo $dt- > format( DateTime::RFC2822 );
First the code creates a new DateTimeZone object representing the Los Angeles time zone, then it creates
th
a new DateTime object representing midnight, 13 Feb 1948 in that time zone. Next the code calls the
DateTime object ’ s modify() method. This very handy method accepts a modification string in the same
format passed to strtotime() and adjusts the date and time accordingly.
Finally, the code calls the DateTime object ’ s format() method to return the date as a string. format()
takes the same type of format string as the date() function. In this case a class constant, DateTime::
RFC2822 , is used to format the date in RFC2822 format — that is, “ D, d M Y H:i:s O ” . Notice how
the time zone offset in the displayed date string is eight hours behind GMT — that is, Los Angeles time.
The DateTime class currently lacks some useful functionality; however, if you prefer the object - oriented
approach, or need to work with dates outside the usual 1901 – 2038 year range, it ’ s well worth a look.
For more information on DateTime and related classes, see http://www.php.net/manual/en/book
.datetime.php .
Working with HTTP
Web servers and browsers talk to each other using HTTP (Hypertext Transfer Protocol), a set of rules that
govern how to request and retrieve data from a Web server.
Most of the time, you don ’ t need to delve into the workings of HTTP, because HTTP communication
happens automatically whenever a visitor visits your Web page or PHP script. However, occasionally it
can be useful to understand some of the processes involved in HTTP, because PHP lets you have some
control over these processes. For example, if you understand how HTTP response headers work, you can
use your PHP script to create your own custom response headers allowing the script to display an
image, or redirect the browser to a new page, for example.
488
9/21/09 9:15:35 AM
c16.indd 488 9/21/09 9:15:35 AM
c16.indd 488