Practical Web Programming

Friday, December 26, 2008

PHP: How to Display The Current Month in Calendar Style

Displaying the current month in a calendar style is very handy and user-friendly for a website, specially for a blog. Using a calendar-style navigation your visitors can easily navigate through your previous posts and articles.

Fortunately, in PHP, this seemingly difficult task in HTML is relatively easy. Just by using a nested For Loop and PHP's Date functions, use can build your own calendar.

Here's the simple source code.

<?php
$now = getdate(time());
$time = mktime(0,0,0, $now['mon'], 1, $now['year']);
$date = getdate($time);
$dayTotal = cal_days_in_month(0, $date['mon'], $date['year']);

print '<table><tr><td colspan="7"><strong>' . $date['month'] . '</strong></td></tr>';
for ($i = 0; $i < 6; $i++)
{
print '<tr>';
for ($j = 1; $j <= 7; $j++)
{
$dayNum = $j + $i*7 - $date['wday'];
print '<td';
if ($dayNum > 0 && $dayNum <= $dayTotal)
{
print ($dayNum == $now['mday']) ? ' style="background: #aaa;">' : '>';
print $dayNum;
}
else
{
print '>';
}
print '</td>';
}
print '</tr>';
if ($dayNum >= $dayTotal && $i != 6)
{
break;
}
}
print '</table>';
?>

Here's how the calendar will look like.


To make it fancier, all you have to do now is use CSS to add colors and styles.

0 comments:

Recent Post