1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[PHP]Date drop down with today pre-selected

Discussion in 'HTML, Graphics & Programming' started by LazyManc, 25 Jan 2006.

  1. LazyManc

    Wise Guy

    Joined: 21 May 2003

    Posts: 1,365

    Anyone got a regular code snippet they use for this?

    There's got to be a more elegant way than the following:
    Code:
    $nowDate = date("d");
    $nowMonth = date("m");
    $nowYear = date("Y");
    
    for ($i = 1; $i <= 9; $i++)
    {
    	if ($nowDate == "0$i")
    	{
    		echo "<option value='0$i' selected=\"selected\">0$i</option>\n";
    	}
    	else
    	{
    		echo "<option value='0$i'>0$i</option>\n";
    	}
    }
    
    for ($i = 10; $i <= 31; $i++)
    {
    	if ($nowDate == $i)
    	{
    		echo "<option value='$i' selected=\"selected\">$i</option>\n";
    	}
    	else
    	{
    		echo "<option value='$i'>$i</option>\n";
    	}
    }
    
    Especially considering it doesn't even take into account how many days in the month...
     
  2. Ozias

    Gangster

    Joined: 21 Oct 2003

    Posts: 228

    I'd replace the code with:

    Code:
    $nowYear = date("Y");
    $nowMonth = date("n");
    $nowDate = date("j");
    $daysInMonth = date("t");
    
    $outputHTML = "";
    
    for($i=1;$i<=$daysInMonth;$i++)
    {
    	// select today's date	
    	$selection = ($nowDate == $i) ? " selected=\"selected\"" : "";
    	
    	// zero pad dates less than 10
    	$date = ($i<10) ? "0".$i : $i;
    	
    	$outputHTML.= "<option value=\"$date\"$selection>$date</option>\n";
    }
    echo $outputHTML;
    
     
    Last edited: 26 Jan 2006
  3. LazyManc

    Wise Guy

    Joined: 21 May 2003

    Posts: 1,365

    Cheers, much more concise.

    Thinking about it I don't actually need the $daysInMonth as in this particular situation I need all variants as i'm searching other months too - i'll have to validate the full date once the form is submitted.