David Dalvin David Dalvin - 1 year ago 81
MySQL Question

Ranging date equal to today date

asking about Date function in php
I want to make a date range in a week (monday-saturday) that the date follow equal to today date in a dropdown option. Let say today 16 Aug then the range will be start in 15 Aug - 20 Aug, 22 Aug - 27, 29 Aug - 3 Sept, and so on.

I use this syntax

for ($i = 0; $i < 8; $i++) {
echo '<option value="'.date("Ymd", strtotime("$i weeks monday")).'">'.date("d F", strtotime("$i weeks monday"))." - ".date("d F", strtotime("$i weeks saturday")).'</option>';

It works perfect only in Monday, but the next day when I open the web, it shows next week monday for all option. It seems that when monday passed, that monday is out of the list in this week and next monday become this weeks monday. It is a bug with strtotime or there is a better strtotime syntax to use ? If possible, I want to avoid using if to check date, but if is not, then are there any possible simple syntax to use in strtotime?

Answer Source

This is difficult to do with strtotime() and doubly so as a one-liner. Using DateTime() and it's related classes gets this to be straightforward, though.

$start    = new DateTimeImmutable('Monday this week');
$end      = $start->add(new DateInterval('P8W'));
$interval = new DateInterval('P1W');
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $week) {
    $monday   = $week->format('Ymd');
    $saturday = $week->modify('next Saturday')->format('Ymd');

    printf('<option value="%s">%s - %s</option>', $monday, $monday, $saturday);


What happens here is:

  1. Use DateTimeImmutable() to create our start date which is the Monday of the current week
  2. Set our end date to be 8 weeks from now (using DateInterval())
  3. Set the interval for our loop to be one week time periods
  4. Put it all into a DatePeriod() object that we can iterate through
  5. Get the format for our Monday date
  6. Get the format for our Saturday date
  7. Echo it out in an <option> tag (using printf() so it is more readable in our code)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download