简体   繁体   中英

PHP Select option return 2 months ago from current month

Hi I would like to know.

how do I get two months from current month Allocated with 1-15 and 16 to 31

I need output something like this:

<option value="2014-09-15">September 15, 2014</option>
<option value="2014-09-30">September 30, 2014</option>
<option value="2014-10-15">October 15, 2014</option>
<option value="2014-10-30">October 30, 2014</option>

I have sample code but its output 12 months

<?php

for ($i = 0; $i <= 11; ++$i) 
{
$time = strtotime(sprintf('+%d months', $i));
$value = date('m', $time);
$label = date('F', $time);

//if month is set stay on that month

if($month==$value)
{ printf('<option value="%s" selected="selected">%s</option>' , $value, $label);
}
else
{printf('<option value="%s">%s</option>', $value, $label);}
}

?>

For example:

$currentMonth = date("n");
for($i=1;$i<3;$i++) {
    $monthNum = $currentMonth - $i;
    if($monthNum<1)
        $monthNum = 12 - $monthNum;
    $monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
    //here use $monthNum and $monthName for output
    print "<option>......</option>";
}

Use function date, which is more easy and spares you the loop...

http://de2.php.net/manual/en/function.date.php

Some theory first:

$currentMonth = date("t", time());

This returns wether 31, 30 or 28/29 depending on month given in time parameter. time() returns a unix-timestamp that is without any parameter just "now" so its the current month.

If we want the amount of days from the next month do the same again just adding seconds to time(), that is enough to reach the next month... so 32 days will in any case bring you to the exact next month...

Sidenote: 1 hour has 3600 seconds * 24 = 1 day has 86400.

$nextMonth = date("t", time() + (86400 * 32)); //+32 days will guarantee next month

Now I present you the entire solution, pretty much means your entire output can be generated like this:

$timeNow = time();
$timeNextMonth = $timeNow + (86400 * 32); //+ 32 days

echo '
    <select name="date">
        <option value="' . date("Y-m-15", $timeNow) . '">' . date("F 15, Y", $timeNow) . '</option>
        <option value="' . date("Y-m-t", $timeNow) . '">' . date("F t, Y", $timeNow) . '</option>
        <option value="' . date("Y-m-15", $timeNextMonth) . '">' . date("F 15, Y", $timeNextMonth) . '</option>
        <option value="' . date("Y-m-t", $timeNextMonth) . '">' . date("F t, Y", $timeNextMonth) . '</option>
    </select>
';

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