Calendar Construction with PHP
(Page 1 of 2 )
In this fifth part of an eight-part series on handling date and time with PHP, you'll learn how to create a monthly calendar and validate dates and times. We'll also start discussing the date() class. This article is excerpted from chapter 12 of the book
Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
Creating a Monthly Calendar
These days, grid-based monthly calendars seem to be one of the most commonly desired Web site features, particularly given the popularity of time-based content such as blogs. Yet creating one from scratch can be deceivingly difficult. Thankfully,Calendar handles all of the tedium for you, offering the ability to create a grid calendar with just a few lines of code. For example, suppose we want to create a calendar for the present month and year, as shown in Figure 12-1.
The code for creating this calendar is surprisingly simple, and is presented in Listing 12-1. An explanation of key lines follows the code, referring to their line numbers for convenience.

Figure 12-1. A grid calendar for April, 2006
Listing 12-1. Creating a Monthly Calendar
01 <?php
02 require_once 'Calendar/Month/Weekdays.php';
03
04 $month = new Calendar_Month_Weekdays(2006, 4, 0);
05
06 $month->build();
07
08 echo "<table cellspacing='5'>\n";
09 echo "<tr><td class='monthname' colspan='7'>April, 2006</td></tr>";
10 echo "<tr><td>Su</td><td>Mo</td><td>Tu</td><td>We</td>
11 <td>Th</td><td>Fr</td><td>Sa </td></tr>";
12 while ($day = $month->fetch()) {
13 if ($day->isFirst()) {
14 echo "<tr>";
15 }
16
17 if ($day->isEmpty()) {
18 echo "<td> </td>";
19 } else {
20 echo '<td>'.$day->thisDay()."</td>";
21 }
22
23 if ($day->isLast()) {
24 echo "</tr>";
25 }
26 }
27
28 echo "</table>";
29 ?>
Line 02: Because we want to build a grid calendar representing a month, theCalendar_Month_Weekdaysclass is required. Line 02 makes this class available to the script.
Line 04: TheCalendar_Month_Weekdaysclass is instantiated, and the date is set to April, 2006. The calendar should be laid out from Sunday to Saturday, so the third parameter is set to0, which is representative of the Sunday numerical offset (1for Monday,2for Tuesday, and so forth).
Line 06: Thebuild()method generates an array consisting of all dates found in the month.
Line 12: Awhileloop begins, responsible for cycling through each day of the month.
Lines 13–15: If$Dayis the first day of the week, output a<tr>tag.
Lines 17–21: If$Dayis empty, output an empty cell. Otherwise, output the day number.
Lines 23–25: If$Dayis the last day of the week, output a </tr>