简体   繁体   中英

Selectbox Months and Years starting with current month in PHP

I'm hoping you guys can help me out with a PHP and Wordpress question. Currently I have 2 selectboxes, on from date and another to date thats lists both a month and year. Currently the dates start at January of the current year, but i need them to start at the current month and year, then print for 2 years.

Here's the current code:

<div class="medium-4 small-6 columns">
  <label class="align-left">
    From:
    <?php
      $select_month_control = '<select name="from_date">';
      for($x = date("Y"); $x <= date("Y", strtotime('+1 year')); $x++) {
        for($y = 1; $y <= 12; $y++) {
          $month_val = $x.str_pad($y, 2, "0", STR_PAD_LEFT).'01';
          $select_month_control.= '<option value="' . $month_val . '" ';
          if ($from_date === $month_val) {
            $select_month_control .= 'selected="selected">';
          }
          else {
            $select_month_control .= '>';
          }
          $select_month_control.= date('F',mktime(0,0,0,$y,1,$year)). " " . $x .' </option>';
        }
      }
      $select_month_control.= '</select>';
      echo $select_month_control;
    ?>
  </label>
</div>
<div class="medium-4 small-6 columns">
  <label class="align-left">
    To:
    <?php
      $select_month_control = '<select name="to_date">';
      $max_x = date("Y", strtotime('+2 year'));
      for($x = date("Y"); $x <= $max_x; $x++) {
        for($y = 1; $y <= 12; $y++) {
          $month_val = $x.str_pad($y, 2, "0", STR_PAD_LEFT).'01';
          $select_month_control.= '<option value="' . $month_val . '" ';
          if ($to_date === $month_val) {
            $select_month_control .= 'selected="selected">';
          }
          else if (empty($to_date) && $x == $max_x && $y === 12) {
            $select_month_control .= 'selected="selected">';
          }
          else {
            $select_month_control .= '>';
          }
          $select_month_control.= date('F',mktime(0,0,0,($y + 1),0,$year)). " " . $x .' </option>';
        }
      }
      $select_month_control.= '</select>';
      echo $select_month_control;
    ?>
  </label>
</div>

So if the site was visited today the select box would start with December 2015 and end with December 2017 with all the months in between. It would also be super helpful if someone could point me in the right direction on how to change the To date to be the last day of the month as opposed to the first day of the month.

Any thoughts would be appreciated.

Thanks so much!

Maybe you can use a DateTime , a DateInterval and a DatePeriod to generate the dates for the select elements.

For the DateInterval you can specify 1 month like this: DateInterval('P1M');

'P1M' stands for:

P for "period

1 for duration

M for months

http://php.net/manual/en/dateinterval.construct.php

You can then create a DatePeriod and use a foreach loop to create the <option> elements.

I have added a parameter $formatUseLastDayOfMonth to set the 'To' date to be the last day of the month. This is an option which can be specified in the format method using the t option.

From the documentation:

Use t for the number of days in the given month ( function.date )

Because you use the select element 2 times, I have created a function which returns the select element as a string.

For example:

<?php
/**
 * Create html select element which will contain options
 * for the given upcoming $numberOfMonths. The current month will be the default.
 *
 * @param int $numberOfMonths
 * @param int $selectedMonth
 * @param bool $formatUseLastDayOfMonth
 *
 * @return string
 */
function getSelectForMonths($numberOfMonths, $selectedMonth = 0, $formatUseLastDayOfMonth = false)
{
    // Add 1 month extra because the $datePeriod we are about to loop excludes the endDate
    $numberOfMonths+=1;
    $dateFormat = $formatUseLastDayOfMonth ? "Ymt" : "Ym01";
    $end = new DateTime();
    $end->modify(sprintf("+%s month", $numberOfMonths));

    $datePeriod = new DatePeriod(
        new DateTime(),
        new DateInterval('P1M'),
        $end
    );

    $selectMonthControl = '<select name="from_date">';
    $monthCounter = 0;
    foreach ($datePeriod as $date) {
        $selectMonthControl .= sprintf(
            "<option value='%s'%s>%s</option>",
            $date->format($dateFormat),
            $selectedMonth === $monthCounter ? 'selected="selected"' : '',
            $date->format('F Y')
        );
        $monthCounter++;
    }
    $selectMonthControl .= "</select>";

    return $selectMonthControl;
}
?>

And then you can use it like this:

<div class="medium-4 small-6 columns">
    <label class="align-left">
        From:
        <?php echo getSelectForMonths(24); ?>
    </label>
</div>
<div class="medium-4 small-6 columns">
    <label class="align-left">
        To:
        <?php echo getSelectForMonths(24, 24, true); ?>
    </label>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM