<input>
elements of type date
create input fields that let the user enter a date, either using a text box that automatically validates the content, or using a special date picker interface. The resulting value includes the year, month, and day, but not the time
. The time and datetime-local
input types support time and date/time inputs.
The control's UI varies in general from browser to browser; at the moment support is patchy, see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to a simple <input type="text">.
Among browsers that support a custom interface for selecting dates is the Chrome/Opera date control, which looks like so:
The Edge date control looks like this:
The Firefox date control looks like this:
Value | A DOMString representing a date in YYYY-MM-DD format, or empty |
Events |
change and input
|
Supported Common Attributes |
autocomplete , list , readonly , and step
|
IDL attributes |
list , value , valueAsDate , valueAsNumber . |
Methods |
select() , stepDown() , stepUp()
|
A DOMString
representing the value of the date entered into the input. You can set a default value for the input by including a date inside the value
attribute, like so:
<input id="date" type="date" value="2017-06-01">
One thing to note is that the displayed date format differs from the actual value
— the displayed date format will be chosen based on the set locale of the user's browser, whereas the date value
is always formatted yyyy-mm-dd
.
You can also get and set the date value in JavaScript using the input element's value
property, for example:
var dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01';
This code locates the first <input>
element whose type
is date
and sets its value to the date 2017-06-01 (June 1, 2017).
In addition to the attributes common to all <input>
elements, "date"
inputs offer the following attributes:
Attribute | Description |
---|---|
max | The latest date to accept |
min | The earliest date to accept |
readonly | Whether or not the input's contents are read-only |
step | The stepping interval to use, such as when clicking up and down spinner buttons, as well as for validation |
max
The latest date to accept. If the value
entered into the element is later than this date, the element fails constraint validation. If the value of the max
attribute isn't a valid string which follows the format "yyyy-MM-dd"
, then the element has no maximum value.
This value must specify a date string earlier than or equal to the one specified by the min
attribute.
min
The earliest date to accept; dates earlier than this will cause the element to fail constraint validation. If the value of the min
attribute isn't a valid string which follows the format "yyyy-MM-dd"
, then the element has no minimum value.
This value must specify a date string later than or equal to the one specified by the max
attribute.
readonly
A Boolean attribute which, if present, means this field cannot be edited by the user. Its value
can, however, still be changed from JavaScript code that directly sets the value of the HTMLInputElement.value
property.
Note: Because a read-only field cannot have a value, required
does not have any effect on inputs with the readonly
attribute also specified.
step
The step
attribute is a number that specifies the granularity that the value must adhere to, or the special value "any"
, which is described below. Only values which are equal to the basis for stepping (min
if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid.
A string value of "any"
means that no stepping is implied, and any value is allowed (barring other constraints, such as min
and max
).
Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.
For date
inputs, the value of step
is given in days, with a scaling factor of 86,400,000 (since the underlying numeric value is in milliseconds). The default value of step
is 1, indicating 1 day.
At this time, it's unclear what a value of "any"
means for step
when used with date
inputs. This will be updated as soon as that information is determined.
Date inputs sound convenient at first glance — they provide an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale. However, there are issues with <input type="date">
because of the limited browser support.
We'll look at basic and more complex uses of <input type="date">
, then offer advice on mitigating the browser support issue later on (see Handling browser support). Of course, hopefully over time browser support will become more ubiquitous, and this problem will fade away.
The simplest use of <input type="date">
involves a basic <input>
and <label>
element combination, as seen below:
<form> <div> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday"> </div> </form>
You can use the min
and max
attributes to restrict the dates that can be chosen by the user. In the following example we are setting a minimum date of 2017-04-01
and a maximum date of 2017-04-30
:
<form> <div> <label for="party">Choose your preferred party date:</label> <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30"> </div> </form>
The result here is that only days in April of 2017 can be selected — only the "days" part of the text value will be editable, and dates outside April can't be scrolled to in the date picker widget.
Note: You should be able to use the step
attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.
<input type="date">
doesn't support form sizing attributes such as size
. You'll have to resort to CSS for sizing needs.
By default, <input type="date">
does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text
) enter an invalid date (e.g. the 32nd of April).
If you use min
and max
to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you'll have to check the results to be sure the value is within these dates, since they're only enforced if the date picker is fully supported on the user's device.
In addition, you can use the required
attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let's look at an example — here we've set minimum and maximum dates, and also made the field required:
<form> <div> <label for="party">Choose your preferred party date (required, April 1st to 20th):</label> <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-20" required> <span class="validity"></span> </div> <div> <input type="submit"> </div> </form>
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here's a screenshot for those of you who aren't using a supporting browser:
Here's the CSS used in the above example. Here we make use of the :valid
and :invalid
CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a <span>
next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.
div { margin-bottom: 10px; display: flex; align-items: center; } label { display: inline-block; width: 300px; } input:invalid+span:after { content: '✖'; padding-left: 5px; } input:valid+span:after { content: '✓'; padding-left: 5px; }
Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd
. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:
ddmmyyyy
dd/mm/yyyy
mm/dd/yyyy
dd-mm-yyyy
mm-dd-yyyy
Month dd yyyy
One way around this is to put a pattern
attribute on your date input. Even though the date input doesn't use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
<form> <div> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"> <span class="validity"></span> </div> <div> <input type="submit"> </div> </form>
If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern nnnn-nn-nn
, where n
is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm
(whereas we want yyyy-mm-dd
). So we still have a problem.
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls (<select>
elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
In this example we create two sets of UI elements for choosing dates: a native <input type="date">
picker and a set of three <select>
elements for choosing dates in older browsers that don't support the native input.
The HTML looks like so:
<form> <div class="nativeDatePicker"> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday"> <span class="validity"></span> </div> <p class="fallbackLabel">Enter your birthday:</p> <div class="fallbackDatePicker"> <span> <label for="day">Day:</label> <select id="day" name="day"> </select> </span> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"> </select> </span> </div> </form>
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">
, we create a new <input>
element, set its type
to date
, then immediately check what its type is set to — non-supporting browsers will return text
, because the date
type falls back to type text
. If <input type="date">
is not supported, we hide the native picker and show the fallback picker UI (<select>
) instead.
// define variables var nativePicker = document.querySelector('.nativeDatePicker'); var fallbackPicker = document.querySelector('.fallbackDatePicker'); var fallbackLabel = document.querySelector('.fallbackLabel'); var yearSelect = document.querySelector('#year'); var monthSelect = document.querySelector('#month'); var daySelect = document.querySelector('#day'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createElement('input'); test.type = 'date'; // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); } function populateDays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while(daySelect.firstChild){ daySelect.removeChild(daySelect.firstChild); } // Create variable to hold new number of days to inject var dayNum; // 31 or 30 days? if(month === 'January' || month === 'March' || month === 'May' || month === 'July' || month === 'August' || month === 'October' || month === 'December') { dayNum = 31; } else if(month === 'April' || month === 'June' || month === 'September' || month === 'November') { dayNum = 30; } else { // If month is February, calculate whether it is a leap year or not var year = yearSelect.value; var leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; dayNum = leap ? 29 : 28; } // inject the right number of new <option> elements into the day <select> for(i = 1; i <= dayNum; i++) { var option = document.createElement('option'); option.textContent = i; daySelect.appendChild(option); } // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when you // change the year if(previousDay) { daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if(daySelect.value === "") { daySelect.value = previousDay - 1; } if(daySelect.value === "") { daySelect.value = previousDay - 2; } if(daySelect.value === "") { daySelect.value = previousDay - 3; } } } function populateYears() { // get this year as a number var date = new Date(); var year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for(var i = 0; i <= 100; i++) { var option = document.createElement('option'); option.textContent = year-i; yearSelect.appendChild(option); } } // when the month or year <select> values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = function() { populateDays(monthSelect.value); } monthSelect.onchange = function() { populateDays(monthSelect.value); } //preserve day selection var previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = function() { previousDay = daySelect.value; }
Note: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.
Specification | Status | Comments |
---|---|---|
HTML Living Standard The definition of '<input type="date">' in that specification. | Living Standard | |
HTML5 The definition of '<input type="date">' in that specification. | Recommendation |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 20 | 12 | 57 | No | 11 | No
|
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | 57 | 11 | 5 | ? |
<input>
element and the interface used to manipulate it, HTMLInputElement
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date