Like most programming languages, PHP comes with a fairlyfull-featured API for date and time value manipulation. You've probablyused it in your applications, but never bothered to look too closely atit. Well, here's your chance to rectify that mistake - this articledelves into the date/time API in depth, uncovering some hidden nuggetsand demonstrating how it can be used to simplify date and timeprocessing in your PHP scripts.
The next few rows are all generated automatically. The
first order of business is to place the first day of the month on the corresponding day. Since I already have a $firstDayOfMonth variable, I've used a simple loop to fill all the cells prior to that day with non-breaking spaces.
// start printing dates
// display blank spaces until the first day of the month
for ($x=1; $x<=$firstDayOfMonth; $x++)
// this comes in handy to find the end of each 7-day block
echo "<td><font face=Arial
The $rowCount variable is simultaneously keeping track
of the number of slots (cells) being filled up - I'll use this a little further down to determine when the end of the week has been reached.
Once the first day of the month is determined, another "for" loop (iterating from 1 to the number of days in the month) is used to generate the remaining rows and cells of the table. The $rowCount and $dayCount variables are incremented at each stage, and the $rowCount variable is divided by 7 to find out when the seven slots available in each row are filled up.
// counter to track the current date
while ($dayCount <= $this->totalDays[$this->currMonth])
// use this to find out when the 7-day block is complete and display a new row
if ($rowCount % 7 == 0)
// print date
// if today, display in different colour
if ($dayCount == date("j") && $this->currYear == date("Y")
&& $this->currMonth == date("n"))
echo "<td align=center bgcolor=Silver><font face=Arial size=-1>$dayCount</font>";
echo "<td align=center><font face=Arial size=-1>$dayCount</font>";
// increment counters
Notice that I've inserted an "if" statement into the
loop to display the current date in a different colour, if a match is found.
Here's an example of how this class might be used:
$cal = new Calendar(2002, 12);
And here's what it would look like:
Pretty cool, huh?
This is just one example of the myriad uses to which PHP's date functions can be put. There are many more; I'll leave them to your imagination. Until next time...be good! Note: All examples in this article have been tested on Linux/i586 with Apache 1.3.20 and PHP 4.1.1. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!