How to use strtotime() function In PHP

In this approach, we are using PHP’s strtotime function to set the start and end dates for the month. We then iterate through each day using loops, filling in empty cells before and after the month’s days to align them correctly in a grid by weeks.

Example: The below example uses strtotime function to display days in a grid by weeks in PHP.

PHP
<?php
$start_date = strtotime('2024-05-01');
$end_date = strtotime('2024-05-31');
echo '<table border="1">';
echo '<tr><th>Sun</th><th>Mon</th>
<th>Tue</th><th>Wed</th><th>Thu</th>
<th>Fri</th><th>Sat</th></tr>';
$current_date = $start_date;
$first_day_of_week = date('D', $start_date);
$week_day_index = ['Sun', 'Mon', 'Tue',
                   'Wed', 'Thu', 'Fri', 'Sat'];
$day_index = array_search($first_day_of_week,
                          $week_day_index); 
echo '<tr>';
for ($j = 0; $j < $day_index; $j++) {
    echo '<td></td>';
}
for ($i = 1; $current_date <= $end_date; $i++) {
    echo '<td>' . date('d', $current_date) .'</td>';
    $current_date = strtotime('+1 day',
                              $current_date);
    $current_day = date('D', $current_date);
    if ($current_day == 'Sun') {
        echo '</tr><tr>';
    }
}
while ($current_day != 'Sat') {
    echo '<td></td>';
    $current_day = date('D', strtotime('+1 day',
                             $current_date));
}
echo '</tr>';
echo '</table>';
?>

Output:

How to Display Days in a Grid by Weeks in PHP?

Displaying days in a grid by weeks consists of iterating over each day within a specified time range, organizing them into rows representing weeks and columns representing days of the week.

Below are the approaches to display dates in a grid by weeks in PHP:

Table of Content

  • Using strtotime function
  • Using DateTime objects and DateInterval

Similar Reads

Using strtotime() function

In this approach, we are using PHP’s strtotime function to set the start and end dates for the month. We then iterate through each day using loops, filling in empty cells before and after the month’s days to align them correctly in a grid by weeks....

Using DateTime objects and DateInterval

In this approach, we are using DateTime objects to set the start and end dates for the month of May 2024. We then iterate through each day using DateInterval to increment the date and display days in a grid format, with empty cells for days outside the month’s range....