3.3. Utilizing Date and Time Input Fields

You want to provide a user with a form to specify a date and/or time—for example, when scheduling an appointment.

HTML5 provides a number of new input types to assist in date and time entry.

This first solution uses the input element with the HTML5 type value of datetime to display both a date-picker widget and a time spinner control in combination, as shown in Figure 3-8:

<form>
    <p><label>Appointment Date and Time <input type="datetime"
        name="dateAndTime"></label></p>
    <p><button type="submit">Submit</button></p>
</form>

To present the date and time input fields separately, as shown in Figures 3-9 and 3-10, use separate input fields with the HTML5 type values date and time:

<form>
    <fieldset>
        <legend>Appointment Request</legend>
        <p><label>Date <input type="date" name="date"></label></p>
        <p><label>Time <input type="time" name="time"></label></p>
    </fieldset>
    <p><button type="submit">Submit</button></p>
</form>

The datetime, date, and time family of input types, which also includes month, week, and datetime-local, are excellent proof that new features in HTML5 are based on what web designers and developers have been doing for years with various JavaScript libraries and other solutions.

Opera has been the leader in generating date and time controls, rendering a calendar-based date-picker control for date and a time spinner control for time, and many expect other browsers to eventually follow its lead.

Webkit-based desktop browsers recently introduced support for these input types, using spinners for both. User agents that do not support these input types revert to a text input field.

For a look at browser support for the date and time input types, see Table 3-3.

Like all other form inputs, you can specify a value to be displayed when the page is rendered. The value for the date input type must be a valid date string, such as 2010-12-31, which represents December 31, 2010.

The value for the time input type must be a valid time string, such as 23:59:59, which represents 11:59 P.M., one second before midnight.

Finally, the value for the datetime input type must be a valid global date and time string, such as 2010-12-31T23:59:59Z, which represents one second before midnight UTC on December 31, 2010.

For more information on valid date and time values, see the HTML5 specification at http://www.w3.org/TR/html5/common-microsyntaxes.html#dates-and-times.