Last active
October 17, 2023 19:29
-
-
Save Vinze/808ec88217729290adca4a06579a55b9 to your computer and use it in GitHub Desktop.
Create an HTML calendar with PHP and Carbon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Make sure Carbon is available | |
function renderCalendar($dt) { | |
// Make sure to start at the beginnen of the month | |
$dt->startOfMonth(); | |
// Set the headings (weeknumber + weekdays) | |
$headings = ['Weeknumber', 'Mondag', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saterday', 'Sunday']; | |
// Create the table | |
$calendar = '<table class="calendar">'; | |
$calendar .= '<caption>'.$dt->format('F Y').'</caption>'; | |
$calendar .= '<tr>'; | |
// Create the calendar headings | |
foreach ($headings as $heading) { | |
$calendar .= '<th class="header">'.$heading.'</th>'; | |
} | |
// Create the rest of the calendar and insert the weeknumber | |
$calendar .= '</tr><tr>'; | |
$calendar .= '<td>'.$dt->weekOfYear.'</td>'; | |
// Day of week isn't monday, add empty preceding column(s) | |
if ($dt->format('N') != 1) { | |
$calendar .= '<td colspan="'.($dt->format('N') - 1).'"> </td>'; | |
} | |
// Get the total days in month | |
$daysInMonth = $dt->daysInMonth; | |
// Go over each day in the month | |
for ($i = 1; $i <= $daysInMonth; $i++) { | |
// Monday has been reached, start a new row | |
if ($dt->format('N') == 1) { | |
$calendar .= '</tr><tr>'; | |
$calendar .= '<td>'.$dt->weekOfYear.'</td>'; | |
} | |
// Append the column | |
$calendar .= '<td class="day" rel="'.$dt->format('Y-m-d').'">'.$dt->day.'</td>'; | |
// Increment the date with one day | |
$dt->addDay(); | |
} | |
// Last date isn't sunday, append empty column(s) | |
if ($dt->format('N') != 7) { | |
$calendar .= '<td colspan="'.(8 - $dt->format('N')).'"> </td>'; | |
} | |
// Close table | |
$calendar .= '</tr>'; | |
$calendar .= '</table>'; | |
// Return calendar html | |
return $calendar; | |
} | |
$dt = Carbon::createFromDate(2018, 05, 01); | |
echo renderCalendar($dt); |
I tried this code for my project, thanks..
Although for a Month where the last day is Sunday, this code add unused td at the end of calendar..
So I add an if at:
// Increment the date with one day
$dt->addDay();
With:
if($dt->day != $daysInMonth) {
$dt->addDay();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good job.