Skip to content

Instantly share code, notes, and snippets.

@Phocacius
Created December 30, 2014 19:07
Show Gist options
  • Save Phocacius/6559dfcd8f9bfe6a6c26 to your computer and use it in GitHub Desktop.
Save Phocacius/6559dfcd8f9bfe6a6c26 to your computer and use it in GitHub Desktop.
A php function that outputs a calendar for a given month and year. Optionally, a heading (e.g. weekdays) can be displayed, and the current day is highlighted. The calendar can be styled via CSS.
<?php
function drawCalendar($year, $month, $heading = null, $forceSixthRow = false) {
$daysInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
$daysInPrevious = date("t", mktime(0, 0, 0, $month-1, 1, $year));
$weekdayOfFirst = date("N", mktime(0, 0, 0, $month, 1, $year)) - 1;
$rows = ($forceSixthRow || $weekdayOfFirst + $daysInMonth > 35) ? 6 : 5;
echo '<table class="calendar" border="1">';
if($heading != null) {
for ($i=0; $i < 7; $i++) {
echo '<th>'.$heading[$i].'</th>';
}
}
for ($row=0; $row < $rows; $row++) {
echo '<tr>';
for ($column=0; $column < 7; $column++) {
$day = 7*$row + $column - $weekdayOfFirst + 1;
if($day < 1) {
$todayClass = date('Y-m-d') == date('Y-m-d', mktime(0, 0, 0, $month-1, $daysInPrevious + $day, $year)) ? ' current' : '';
echo '<td class="inactive'.$todayClass.'">'.($daysInPrevious + $day).'</td>';
} else if($day > $daysInMonth) {
$todayClass = date('Y-m-d') == date('Y-m-d', mktime(0, 0, 0, $month+1, $day - $daysInMonth, $year)) ? ' current' : '';
echo '<td class="inactive'.$todayClass.'">'.($day - $daysInMonth).'</td>';
} else {
$todayClass = date('Y-m-d') == date('Y-m-d', mktime(0, 0, 0, $month, $day, $year)) ? ' class="current"' : '';
echo '<td'.$todayClass.'>'.$day.'</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment