O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dates and Times in Forms

When you need a user to input a date in a form, the best thing to do is to use <select> menus. This generally restricts the possible input to whatever you display in the menus. The specific date or time information you need controls what you populate the <select> menus with.

A Single Menu with One Choice Per Day

If there are a small number of choices, you can have just one menu that lists all of them. Example 9-9 prints a <select> menu that lets a user pick one day in the coming week. The value for each option in the menu is an epoch timestamp corresponding to midnight on the displayed day.

Example 9-9. A day choice <select> menu

$midnight_today = mktime(0,0,0);
print '<select name="date">';
for ($i = 0; $i < 7; $i++) {
    $timestamp = strtotime("+$i day", $midnight_today);
    $display_date = strftime('%A, %B %d, %Y', $timestamp);
    print '<option value="' . $timestamp .'">'.$display_date."</option>\n";
}
print "\n</select>";

On October 20, 2004, Example 9-9 prints:

<select name="date"><option value="1098244800">Wednesday, October 20, 2004</option>
<option value="1098331200">Thursday, October 21, 2004</option>
<option value="1098417600">Friday, October 22, 2004</option>
<option value="1098504000">Saturday, October 23, 2004</option>
<option value="1098590400">Sunday, October 24, 2004</option>
<option value="1098676800">Monday, October 25, 2004</option>
<option value="1098763200">Tuesday, October 26, 2004</option>

If you're using the input_select( ) form helper function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required