MOVED: My blog is now at

Code bits: PHP date year box script

Creating a warranty registration form for the proud owners of a new LCD panel should have been a very straightforward job. Well, actually it was, but that sort of interrupts the flow of this post a bit, so I’ll skim over that inconvenient fact.

For the ‘date of purchase’ field, I simply added the day and months items as <select> form controls. Then I got to the ‘year’ box, and realised that soon we’ll be leaving 2008 behind like a piece of temporal rubbish, and embracing the glistening newborn that will be 2009. I know the client wouldn’t really appreciate having to come back to me a month after his site goes live just so I can add a new year to the form, so I decided on the only sensible course of action a quality web designer like me could take, and made a super-simple php script to write the year into the form.

Here’s the php function:

function writePurchaseYear()
    $currentDate = getDate();
    $currentYear = $currentDate['year'];
    $startYear = 2008;
    $output = "<option value=\"2008\">2008</option>\n";

    if($currentYear - $startYear > 0)
        for($i = $currentYear; $i >= $startYear; $i--)
            $output = $output . "<output value=\"$i\">$i</option>\n";
    echo $output;

So, put that somewhere on the page that’s going to use it, and then, where you need the actual form control to be on the page, you need to put:

<select name="purchaseyear" id="purchaseyear">
    <option selected>----</option>
    <?php writePurchaseYear();?>             

So there you have it. HTH, and all that.

Labels: ,

Jason posted this on Thursday, November 13, 2008 at 3:44 pm. Leave comment.

Blogmarks button Digg button furl button magnolia button Google Bookmarks button StumbleUpon button Yahoo MyWeb button

Number of comments: 1

Anonymous Professional Web Development Services says:

I am very interested in you post. It is very helpful and useful for me. Thanks for share this valuable post.

This comment was posted on 12:59 pm