使用当前月份和当前年份预填充下拉框

时间:2019-04-29 15:48:59

标签: php

我需要在PHP中自动填充一个下拉框,需要以特定方式设置其格式...

从当前月份和当前年份开始,然后以每月间隔显示21个条目。.....

 <select name="date" id="date">
<option value="1/4/2019">April 2019</option> (Current Month Current Year)
<option value="1/5/2019">May 2019</option>
<option value="1/6/2019">June 2019</option>
<option value="1/7/2019">July 2019</option>
<option value="1/8/2019">August 2019</option>
<option value="1/9/2019">September 2019</option>
<option value="1/10/2019">Ocotber 2019</option>
<option value="1/11/2019">November 2019</option>
<option value="1/12/2019">December 2019</option>
<option value="1/1/2020">January 2020</option>
<option value="1/2/2020">February 2020</option>
<option value="1/3/2020">March 2020</option>
<option value="1/4/2020">April 2020</option>
<option value="1/5/2020">May 2020</option>
<option value="1/6/2020">June 2020</option>
<option value="1/7/2020">July 2020</option>
<option value="1/8/2020">August 2020</option>
<option value="1/9/2020">September 2020</option>
<option value="1/10/2020">October 2020</option>
<option value="1/11/2020">November 2020</option>
<option value="1/12/2020">December 2020</option>


I was looking at doing...

$currentmonth = date("F");
$currentyear = date("Y");

Etc.. But feel there is probably an easier way, any help appreicated

3 个答案:

答案 0 :(得分:1)

5.3 +

$d = new \DateTime('first day of this month');
echo  "<select name='date' id='date'>";
for ($i = 0; $i < 21; $i++) {
    $target = $d;
    echo "<option value='".$target->format("1/m/Y")."'>".$target->format("F Y")."</option>";
    $d->modify('first day of next month');
}
echo "</select>";

答案 1 :(得分:0)

支持的版本(PHP 4,PHP 5,PHP 7)

$no_of_iterations = 21;
$time = strtotime(date('Y-m-d'));
echo  "<select name='date' id='date'>";
for($i = 1; $i <= $no_of_iterations; $i++) {
     $date_in = date("Y-m-d", strtotime("+$i month", $time));
    echo "<option value='".date("1/m/Y", strtotime($date_in))."'>".date("F Y", strtotime($date_in))."</option>";
}
echo "</select>";

答案 2 :(得分:0)

所以您想看一下strtotime(),这一次可以带走一个月。因为您希望它从第一个开始,所以您要从01开始。

请参见下面的代码段...评论应该对它进行足够的解释,我希望.....

$html = buildDateDropDown();

echo $html;

function buildDateDropDown ( ) {

$FirstThisMonth = "01".date('-m-Y'); //Concatonate 01 tith the month & year of this month


$dropDown = "<select class='form-control' id='date' name='date'>\n";  //open your select tag
$dropDown.="\t<option value='$FirstThisMonth' selected>$FirstThisMonth</option>\n"; //first of this month is selected

$loop=1;

while($loop<=21) {

    $value = "01".date('-m-Y', strtotime('-'.$loop.' month')); //strtotime converts - the loop value of one month
    $dropDown.="\t<option value='$value'>$value</option>\n";    //concatonate in your value
    $loop++; //increment the loop

}

$dropDown.="</select>\n"; //close the select

return $dropDown;

}