Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 360
  • Last Modified:

Month Select Box Dynamic Range

Looking to code a select box that will update every month beginning with the current month and going back twelve months.

For example, a select box for this month would have options for Jan '14 - Feb '13.
0
t3chguy
Asked:
t3chguy
  • 3
  • 2
1 Solution
 
Ray PaseurCommented:
While I set up an example for you, read this article.  It will show you everything you need to know about how to do this.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
0
 
Ray PaseurCommented:
Here is an example: http://www.laprbass.com/RAY_temp_t3chguy.php

<?php // RAY_temp_t3chguy.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28332606.html#a39762962

// THE MONTHS
$now = date('Y-m-1');
$old = date('Y-m-1', strtotime("$now - 11 MONTHS"));
$new = date('Y-m-1', strtotime('TODAY'));

// GET THE DATE STRINGS
while ($old <= $new)
{
    $arr[$old] = date("M 'y", strtotime($old));
    $old       = date('Y-m-1', strtotime($old . ' + 1 MONTH'));
}

$arr = array_reverse($arr);

// CREATE THE SELECT OPTIONS
$out = '<select name="month">' . PHP_EOL;
foreach ($arr as $val => $txt)
{
    $out .= '<option value="' . $val . '">' . $txt . '</option>' . PHP_EOL;
}
$out .= '</select)' . PHP_EOL;

// SHOW WHAT WE MADE
echo '<pre>';
echo htmlentities($out);

Open in new window

HTH, ~Ray
0
 
GaryCommented:
Or a simpler way

for($i=0;$i<12;$i++){
	echo "<option>".date("F Y",strtotime("-".$i." Months"))."</option>"; 
}

Open in new window

0
 
Ray PaseurCommented:
@cathal: You might want to test that on several different starting dates.  The term "Month" is ambiguous.  I've found that PHP mostly gets it right when you add or subtract a "Month" during the first 28 days of any month.  After that, the wheels begin to fall off.  If you normalize the date to the first of the month it seems to be right (or at least intuitively correct) every time.

See Ambiguity of the term "Month" for an explanation along with a test script that shows what can happen.
0
 
GaryCommented:
Realised a glitch with my sample, here's a better method that doesn't burp on the 31st.

$tempDate= strtotime(date("Y")."-".date("F")."-15");

for($i=0;$i<12;$i++){
	echo "<option>".date("F Y",strtotime("-".$i." Months",$tempDate))."</option>"; 
}

Open in new window


@Ray
Yeah I realised that, new method above sets a starting date
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now