How to populate weeks from a startdate and endate into a dropdown?

How to populate weeks from a startdate and endate into a dropdown? Let say I want to get all weeks within this month. But then, how do I populate them as weeks into a dropdown?

So far, I've tried this:

<?php
$start = "2016-03-01";
$end = "2016-03-31";    
$first_day = $start.' first Sunday of this month';
$first_day = date_create($first_day);
$first_day = $first_day->format('Y-m-d');
$last_day = $start.' last Saturday of this month';
$last_day = date_create($last_day);
$last_day = $last_day->format('Y-m-d');

if($start != $first_day) {
$date_str = $start.' last Sunday of last month';
$start_date = date_create($date_str);
$start_date = $start_date->format('Y-m-d');
}
else {
$start_date = $start;    
}

if($end != $last_day) {
$date_str = $end.' first Saturday of next month';
$end_date = date_create($date_str);
$end_date= $end_date->format('Y-m-d');
}
else {
$end_date = $end;    
}
?>

//result
//start_date = "2016-02-28";
//end_date= "2016-04-02";

Above code will give me the start date and end date for complete set of weeks in a month where Sunday as the first and Saturday as the last day of a week. But then, I would like to populate the weeks into a dropdown based on the start date and end date. How to do it?

I want to output below values into a dropdown:

<select>
<option value="2016-02-28 to 2016-03-05">Week 1</option>
<option value="2016-03-06 to 2016-03-15">Week 2</option>
<option value="2016-03-13 to 2016-03-19">Week 3</option>
<option value="2016-03-20 to 2016-03-26">Week 4</option>
<option value="2016-03-27 to 2016-04-02">Week 5</option>
</select>

Please advise how to populate above output into a dropdown using jQuery or PHP.

Answers 1

  • Try this:

    <select>
    <?php 
       $start_month = "2016-03-01";
       $end_month   = "2016-03-31";  
       while (strtotime($start_month) <= strtotime($end_month)) {
          $week_start  =  date('Y-m-d',strtotime($start_month.' last Sunday'));
          $week_end    =  date('Y-m-d',strtotime($start_month.' Saturday this week'));
    ?>
    
    <option value='<?php echo $week_start." to ".$week_end; ?>' >
        <?php echo $week_start." to ".$week_end; ?>
    </option>       
    
    <?php   $start_month = date("Y-m-d", strtotime($start_month." +7 days"));
    
    } ?>
    </select>
    

    Hope this helps.


Related Articles