simple calendar script

December 3, 2008

You need to create a simple calendar to be displayed in your website or web applicaiont?

It’s really simple to create a calendar in php, bellow is a small example on how easy it is.

The script gets the current date and builds a table calendar.

You can add day triggers, for example comming from a database, in this case it’s to display a birthdate.

Feel free to use and modify.

****************

<?php
/*
*Calendar script by jorge Alves
* befourdev@gmail.com
* */
$date = time();

$day = date(‘d’, $date) ;
$year = date(‘Y’, $date) ;
$month = ’09’;

#calculate the first day
$first_day = mktime(0,0,0, $month  , 1, $year);

#retrieve the first day
$title = date(‘D’, $first_day);

#Get Month name
$month_name = date(‘F’, $first_day);

#Calculate how many days there are in the month
$days_in_month = date(‘t’,mktime(0,0,0,$month,$month,$year));

#Your birthday birthdate -> you can call any day or add an event::
$birthday = 25;

#Select  on which day of the week it starts the month
switch($title)
{
case “Sun”: $start = 0; break;
case “Mon”: $start = 1; break;
case “Tue”: $start = 2; break;
case “Wed”: $start = 3; break;
case “Thu”: $start = 4; break;
case “Fri”: $start = 5; break;
case “Sat”: $start = 6; break;
}

#Table with our calendar
echo “<table border=1 width=30%>”;
echo “<tr><th colspan=7> $month_name $year  </th></tr>”;
echo “<tr><td width=42>S</td><td width=42>M</td><td width=42>T</td><td width=42>W</td><td width=42>T</td><td width=42>F</td><td width=42>S</td></tr>”;

$counter = 0; // counter for the start fills up the blanks
$rowcounter = 0; //counter for the rows
$daycounter=1; //counter for the month days
echo “<tr>”;
//loop until we reach the end of the month
while ( $daycounter <= $days_in_month )
{
//Draw beginning of row
$output =  ($rowcounter > 6) ?   “<tr>” : “&nbsp;” ;
//resets row counter
$rowcounter = ($rowcounter > 6) ? $rowcounter = 0 : $rowcounter = $rowcounter;
//fill the cells with dates
if  ( $counter < $start )
{
//fill with blank, first day of month starts after
$output .= “<td>&nbsp;</td>”;
}
else
{
//check for birthday
if ($daycounter == $birthday)
{
//prints birthday and adds the daycounter
$output .= “<td style=\”color:blue;\”>$daycounter My Birthday!!</td>”;
$daycounter++;
}
else
{
//prints days and adds the daycounter
$output .=”<td style=\”color:black;\”>$daycounter</td>”;
$daycounter++;
}
}
//Draw end of row
$output .=  ($rowcounter > 6) ?   “</tr>” : “&nbsp;” ;

//echo the calendar
echo  $output;

//ads to rowcounter
$rowcounter++;
//ads to counter
$counter++;
}
//ends calendar table
echo “</table>”;
?>

***********