bluHatter

Coding, Gaming, and Random Knowledge

Programming a PHP Calendar

without comments

Writing an application that tracks time and dates accurately is a common challenge which does not at all fit neatly into our base-10 numbering system. In even the simplest calendar or scheduling application, for example, one must consider at least the following complications:

Leap Years - Every non-millennial year that can be divided evenly by 4, and every millennial year that can be divided by 400 gets 1 extra day in February.

Daylight Savings Time – Due to political legislation dating back to 1895, clocks “spring forward” 1 hour in the Spring, and “fall back” 1 hour in the Fall. Generally this can be handled by simply relying on the server’s system clock, as long as the system clock is set to auto-adjust for DST.

Time Zones – Also known as “Locale”, a thorough scheduling application should allow users to select their preferred time zone, and change it at will.

But even taking all that into account, just wrapping your head around the whole idea of writing a calendar from scratch is a bit daunting. How will you know how many days are in each month? How will you know which day is the first day of the month? Fortunately, the good folks at PHP have provided some very useful functions to help us get started.

For the sake of an example, let’s assume I am trying to find out how to render the month of March, 2011. I can simply use the prebuilt function cal_days_in_month( ) as shown below.

$intNumDays['2011']['03'] = cal_days_in_month(CAL_GREGORIAN, 3, 2011);

That is step 1. Now how do we find out which day is first? This can be accomplished with a call to getdate() as shown below.

$timestamp = strtotime( "03/01/2011" );
$dateparts = getdate( $timestamp );
intFirstDay['2011']['03'] = $dateparts['weekday'];

Pretty simple, right? Now that we know how many days are in March, 2011 and which day it starts on ( Tuesday ), you can easily render the month grid using a standard loop. Want to go back a month, or forward a month? Just change your variables and render it again. Once you have the base set up, writing a calendar becomes a MUCH simpler task.

Written by bluhatter

March 31st, 2011 at 5:48 pm

sonic