How to Create datetime-local Input in HTML Easily
Use the
<input> element with type="datetime-local" to create a date and time picker in HTML. This input lets users select both date and time without a timezone. Example: <input type="datetime-local">.Syntax
The datetime-local input uses the <input> tag with the attribute type="datetime-local". You can add optional attributes like name, id, value, min, and max to control the input.
- type="datetime-local": Specifies the input is for date and time without timezone.
- name: Identifies the input in forms.
- value: Sets the default date and time in
YYYY-MM-DDThh:mmformat. - min and max: Define the allowed date-time range.
html
<input type="datetime-local" name="appointment" id="appointment" value="2024-06-01T14:30" min="2024-01-01T00:00" max="2024-12-31T23:59">
Output
A date and time picker input field with default value June 1, 2024, 14:30, allowing selection only within 2024.
Example
This example shows a simple form with a datetime-local input. The user can pick a date and time, which will be submitted with the form.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Datetime-local Input Example</title> </head> <body> <form> <label for="meeting">Choose meeting date and time:</label><br> <input type="datetime-local" id="meeting" name="meeting" value="2024-06-15T09:00"> <br><br> <button type="submit">Submit</button> </form> </body> </html>
Output
A webpage with a labeled date and time picker defaulting to June 15, 2024, 09:00, and a submit button.
Common Pitfalls
- Not using the correct format for the
value,min, ormaxattributes. It must beYYYY-MM-DDThh:mm(note theTbetween date and time). - Expecting timezone support:
datetime-localdoes not handle timezones. - Older browsers may not support
datetime-local, so fallback or validation might be needed.
html
<!-- Wrong: missing 'T' between date and time --> <input type="datetime-local" value="2024-06-15 09:00"> <!-- Correct: includes 'T' --> <input type="datetime-local" value="2024-06-15T09:00">
Output
The first input may not show the default value correctly; the second input shows the default date and time properly.
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| type | Defines input as datetime-local | |
| value | Sets default date and time (YYYY-MM-DDThh:mm) | |
| min | Minimum allowed date and time | |
| max | Maximum allowed date and time | |
| name | Name for form submission |
Key Takeaways
Use to let users pick date and time without timezone.
The value format must be YYYY-MM-DDThh:mm with a capital 'T' separating date and time.
Add min and max attributes to restrict selectable date and time range.
Not all browsers support datetime-local, so test and provide fallback if needed.
This input does not handle timezones; it is local to the user's device.