Simple date selector generator in php

Jake

Paragon
Joined
Nov 14, 2010
Messages
2,264
Reaction score
2
FP$
246
Sometimes you find yourself needing to collect a date from a user, like their birthday for example.

I coded up a generator and it's free for you to use. It uses semantic HTML5 where possible and keeps your code clean (no line breaks, it's all in one line.)

All you need to do is type:
Code:
<?php generate_date_selector(string $fieldname, string $labelname, int $highyear, int $lowyear);

A production example would look like:
Code:
<?php generate_date_selector("birth", "Birthday", 2014, 1920); ?><br />

The $fieldname variable corresponds to what PHP looks at, so each field is appended with it. The month would be called "birthmonth", the day would be called "birthday", and the year would be called "birthyear".

The $labelname variable is what goes ahead of the selectors in the HTML.
Ex: dH4Hu5z.webp

The $highyear variable is, usually, the current year (soon 2014). This is the highest year available for selection.

The $lowyear variable is the lowest year available for selection. I usually set this at about 1900 just so I have all the options open for people who might use the website.

So, here's the code. Just copy this into a php file and include that file and then you can call the function! Enjoy 🙂

Code:
<?php
<?php
function generate_date_selector($fieldname, $labelname, $highyear, $lowyear)
{
	echo "<label>".$labelname.": </label>";
	$month = array(1 => "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	// month selector
	echo "<select name=\"".$fieldname."month\">";
	for ($currentMonth = 1; $currentMonth <= 12; $currentMonth++) {
		echo "<option value=\"".intval($currentMonth)."\">".$month[$currentMonth]."</option>";
	}
	echo "</select>";
	// day selector
	echo "<select name=\"".$fieldname."day\">";
	for ($currentDay = 1; $currentDay <= 31; $currentDay++) {
		echo "<option value=\"".$currentDay."\">".$currentDay."</option>";
	}
	echo "</select>";
	// year selector
	echo "<select name=\"".$fieldname."year\">";
	for ($currentYear = $highyear; $currentYear >= $lowyear; $currentYear--) {
		echo "<option value=\"".$currentYear."\">".$currentYear."</option>";
	}
	echo "</select>";
}
?>
 
Back
Top Bottom