Sample month at a time code for events calendar

Skip to first unread message

Dec 17, 2006, 12:22:32 AM12/17/06
I am in the process of rewriting one of my first PHP scripts, an event
calendar, and wanted to share the code that is the core of the new
calendar. My current/previous calendar processed data dates only, this
code is intended to use more thrifty event descriptions (3rd saturday,
last tuesday, etc.) as well as traditional one-of dates.

The core here here is quite spartan, no table logic or or db cruft
included (I figure you have our own design ideas/preferences.)


//sample code to generate american calendar format for a given month
// i,e. start of sunday on or before the 1st end on te saturday on or
after the last day.
// makes use of mktime's cool liberal calculation of dates.

// Set sample month and year values:
$mn = date("m");
$yr = date("Y");

// Start calendar logic:

$firstday = date("w",mktime(0,0,0,$mn,1,$yr)); // Get first day of
target month (0=sum 6=set)

$numdays = date("t",mktime(0,0,0,$mn,1,$yr)); // Number of days in
target month

$daystop = $numdays+(6-date("w",mktime(0,0,0,$mn+1,0,$yr))); //
Adjusted last saturday of calendar page (on or after last day of month

//start with american first sunday on or before start of month of
calendar page and end on daystop (saturday)
for($daynum = 1 - $firstday; $daynum <= $daystop; $daynum++) {

//need working date timestamp to work out details of the calendar
$wkdate = mktime(0,0,0,$mn,$daynum,$yr); //the first of the month -
unix value

$wdy = date("w",$wkdate); //day of the week (0 sun - 6 sat)
$wmn = date("m",$wkdate); //month
$wdt = date("d",$wkdate); //date

$wdte = date("D, m/d/Y",$wkdate); //date string of current date "Day,

$ndays = date("t",$wkdate); //# days in working month
$wknum = intval(($wdt-1) / 7)+1; //week number in month

$lastweek = ($wdt > $ndays-7 ? true : false); //last week of month

$curmonth = ($wmn == $mn ? true : false); //current month (for

// display example of what we know:
echo (($wdy % 6)==0 ? "*": ""). //indicate if date is a weekend date
"Date: ".$wdte. //day of week and date
", Week: ".$wknum. //indicate if it is the last week of the month
($lastweek==true? " (last)" : "")."<br />";
if ($wdy == 6) { // divide between american weeks sun-sat (new
echo "<hr />";

Reply all
Reply to author
0 new messages