W3docs

Simple DatePicker-like Calendar

A simple DatePicker-like calendar can be created using the PHP DateTime class and some basic HTML and CSS.

A simple DatePicker-like calendar can be created using the PHP DateTime class and some basic HTML and CSS. Here is an example of how you might create a calendar for the current month:

Example of a simple DatePicker-like Calendar in PHP

<?php
$date = new DateTime();
$currentMonth = $date->format('m');
$currentYear = $date->format('Y');
$numDays = $date->format('t');

echo '<table>';
echo '<tr>';
echo '<th>Sun</th>';
echo '<th>Mon</th>';
echo '<th>Tue</th>';
echo '<th>Wed</th>';
echo '<th>Thu</th>';
echo '<th>Fri</th>';
echo '<th>Sat</th>';
echo '</tr>';

for ($i = 1; $i <= $numDays; $i++) {
  $dayOfWeek = date('w', strtotime("$currentYear-$currentMonth-$i"));
  if ($i == 1) {
    echo '<tr>';
    for ($j = 1; $j <= $dayOfWeek; $j++) {
      echo '<td></td>';
    }
  } elseif ($dayOfWeek == 0) {
    echo '</tr><tr>';
  }
  echo '<td>' . $i . '</td>';
  if ($dayOfWeek == 6 || $i == $numDays) {
    echo '</tr>';
  }
}

echo '</table>';
?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This example creates a table with the days of the week as the headings, and the days of the current month as the table cells. It uses the PHP DateTime class to determine the current month and year, and $date->format('t') to get the number of days in the month. The strtotime() function determines the day of the week for each date, and the loop logic ensures each week starts on a new ```<tr>``` row.

You can style the table using CSS to make it look like a calendar:

table {
  border-collapse: collapse;
  width: 300px;
  font-family: sans-serif;
}
th, td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: center;
}
th {
  background-color: #f4f4f4;
}
td:hover {
  background-color: #e9e9e9;
  cursor: pointer;
}