Return all Mondays between two dates while excluding certain dates from an array

40 Views Asked by At

In php, return all Mondays between two dates. However, exclude certain dates as needed/listed. Then, show all dates, but use the "strike" tag in html to display the dates from the excluded list.

This code returns a decent result, but there must be a more eloquent solution that uses the DateTime functions and a possibly a list of dates to exclude as an array.

`$startDate = date('Y-m-d', strtotime('this monday'));
$endDate = date('Y-m-d', strtotime('2024-05-06'));
$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i)) {
  if ( $i != strtotime('Monday', strtotime('2024-02-19')) &&
    $i != strtotime('Monday', strtotime('2024-03-25')) &&
    $i != strtotime('Monday', strtotime('2024-05-13')) ) {
      echo "<li>";
        echo date('D. M. jS', $i);
      echo "</li>";
    } else {
      // strike through the excluded dates with <s> tag
      echo "<li><s>";
        echo date('D. M. jS', $i);
      echo "</s></li>";
    }
}`
1

There are 1 best solutions below

0
User863 On BEST ANSWER

You can rewrite the code using DateTime like below


$startDate = new DateTime('this monday');
$endDate = new DateTime('2024-05-06');
$excludedDates = ['2024-02-19', '2024-03-25', '2024-05-13'];

$currentDate = clone $startDate;

while ($currentDate <= $endDate) {
    if (!in_array($currentDate->format('Y-m-d'), $excludedDates) && $currentDate->format('l') === 'Monday') {
        echo "<li>" . $currentDate->format('D. M. jS') . "</li>";
    } else {
        echo "<li><s>" . $currentDate->format('D. M. jS') . "</s></li>";
    }

    $currentDate->modify('+1 week');
}