Skip to content

Instantly share code, notes, and snippets.

@Vinze
Last active October 17, 2023 19:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Vinze/808ec88217729290adca4a06579a55b9 to your computer and use it in GitHub Desktop.
Save Vinze/808ec88217729290adca4a06579a55b9 to your computer and use it in GitHub Desktop.
Create an HTML calendar with PHP and Carbon
<?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).'">&nbsp;</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')).'">&nbsp;</td>';
}
// Close table
$calendar .= '</tr>';
$calendar .= '</table>';
// Return calendar html
return $calendar;
}
$dt = Carbon::createFromDate(2018, 05, 01);
echo renderCalendar($dt);
@hadidadkhah
Copy link

Good job.

@pinokio07
Copy link

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