Date Time Picker
- Usage
- Styling
- Step
- Auto Open
- Validation
- Week Numbers
- Initial Position
- Internationalization (i18n)
- Basic Features
- Read-Only & Disabled
- Style Variants
- Usage Patterns
- Best Practices
- Related Components
Date Time Picker is an input field for selecting both a date and a time.
The date and time can be entered directly using the keyboard in the format of the current locale or through the Date Time Picker’s two overlays. The overlays open when their respective fields are clicked or any input is entered when the fields are focused.
Step
Date Time Picker’s step parameter defines the time interval in seconds between the items displayed in the time picker overlay. It also specifies the amount by which the time increases or decreases using the up and down arrow keys when the overlays are disabled.
The default step is one hour (that is, 3600
). Unlike with Number Field, Date Time Picker accepts values that don’t align with the specified step.
new tab
<vaadin-date-time-picker
label="Meeting date and time"
value="2020-06-12T12:30"
.step="${60 * 30}"
></vaadin-date-time-picker>
Note
|
Use Even Steps
The step must divide evenly an hour or a day. For example, "15 minutes", "30 minutes" and "2 hours" are valid steps, while "42 minutes" isn’t.
|
The displayed time format changes based on the step.
new tab
<vaadin-date-time-picker
label="Message received"
value="2020-06-12T15:45:08"
step="1"
></vaadin-date-time-picker>
Step | Format |
---|---|
Less than 60 seconds | HH:MM:SS |
Less than 1 second | HH:MM:SS:FFF |
Note
|
Limit Number of Steps
The overlay doesn’t appear for steps less than 900 seconds (i.e., 15 minutes) to avoid showing an impractical number of choices.
|
Auto Open
The overlay opens automatically when the field is focused using a pointer (i.e., mouse or touch), or when the user types in the field. You can disable this so that the overlay opens only when the toggle button or the Up/Down arrow keys are pressed.
new tab
<vaadin-date-time-picker
label="Meeting date and time"
auto-open-disabled
></vaadin-date-time-picker>
Validation
Date Time Picker provides a validation mechanism based on constraints. Constraints allow you to define criteria that the date must meet to be considered valid. Validation occurs typically when the user initiates a date change, for example by selecting a date from the overlay or through text input followed by Enter. If the date is invalid, the field is highlighted in red, and an error message appears underneath the input.
Below is a list of supported constraints with more detailed information:
Bad Input
Bad input refers to any input that cannot be parsed into a value of the field type. When an unparsable value is entered, the field resets the value to empty and becomes invalid. This constraint is non-configurable and enabled by default.
Required
Required fields are marked with an indicator next to the label, and become invalid if their value is first entered and then cleared.
An instruction text at the top of the form explaining the required indicator is recommended. The indicator itself can be customized with the --lumo-required-field-indicator
style property.
Min & Max Values
The valid input range of Date Time Picker can be restricted by defining min
and max
values. Dates and times before the min
and after the max
aren’t available for selection in the overlay. Helper text can be used to inform the user about the accepted range.
The following example demonstrates how to specify these constraints and provide error messages:
new tab
<vaadin-date-time-picker
required
label="Appointment date and time"
helper-text="Must be within 60 days from today"
.min="${format(this.minDate, `yyyy-MM-dd'T'HH:00:00`)}"
.max="${format(this.maxDate, `yyyy-MM-dd'T'HH:00:00`)}"
.errorMessage="${this.errorMessage}"
@validated="${(event: DateTimePickerValidatedEvent) => {
const field = event.target as DateTimePicker;
const datePicker: DatePicker = field.querySelector('[slot=date-picker]')!;
const timePicker: TimePicker = field.querySelector('[slot=time-picker]')!;
const hasBadDateInput =
!datePicker.value && !!(datePicker.inputElement as HTMLInputElement).value;
const hasBadTimeInput =
!timePicker.value && !!(timePicker.inputElement as HTMLInputElement).value;
if (hasBadDateInput || hasBadTimeInput) {
this.errorMessage = 'Invalid date or time';
} else if (!field.value) {
this.errorMessage = 'Field is required';
} else if (field.value < field.min!) {
this.errorMessage = 'Too early, choose another date and time';
} else if (field.value > field.max!) {
this.errorMessage = 'Too late, choose another date and time';
} else {
this.errorMessage = '';
}
}}"
></vaadin-date-time-picker>
It’s important to ensure an appropriate error message is configured for each constraint violation to provide users with clear feedback.
Custom Validation
For more complex cases where constraint validation isn’t enough, Flow and Hilla offer the Binder API that allows you to define custom validation rules. This is useful, for example, when you want to restrict date selection to weekdays (i.e., Monday - Friday) and time selection to only certain hours. In the following example, try selecting a date that’s on a weekend or a time that’s outside opening hours to see a custom validation message.
new tab
private binder = new Binder(this, AppointmentModel);
private errorMessage = 'The selected day of week or time is not available';
protected override firstUpdated() {
this.binder.for(this.binder.model.startDateTime).addValidator({
message: this.errorMessage,
validate: (startDateTime: string) => {
const date = new Date(startDateTime);
const validWeekDay = date.getDay() >= 1 && date.getDay() <= 5;
return validWeekDay;
},
});
this.binder.for(this.binder.model.startDateTime).addValidator({
message: this.errorMessage,
validate: (startDateTime: string) => {
const time = startDateTime.split('T')[1];
const validTime =
(time >= '08:00' && time <= '12:00') || (time >= '13:00' && time <= '16:00');
return validTime;
},
});
}
protected override render() {
return html`
<vaadin-date-time-picker
label="Appointment date and time"
helper-text="Open Mondays-Fridays, 8:00-12:00, 13:00-16:00"
.step="${60 * 30}"
${field(this.binder.model.startDateTime)}
></vaadin-date-time-picker>
`;
}
Week Numbers
You can configure Date Time Picker to show week numbers in the date picker overlay.
new tab
@query('vaadin-date-time-picker')
private dateTimePicker!: DateTimePicker;
protected override firstUpdated() {
this.dateTimePicker.i18n = {
...this.dateTimePicker.i18n,
firstDayOfWeek: 1,
};
}
protected override render() {
return html`
<vaadin-date-time-picker
label="Meeting date and time"
show-week-numbers
></vaadin-date-time-picker>
`;
}
The week numbers are displayed according to ISO-8601. They can only be displayed with the first day of the week set to Monday.
Initial Position
Date Time Picker’s initial position parameter defines which date is focused in the calendar overlay when the overlay is opened. Use this feature to minimize the need for any additional navigation or scrolling when the user’s input is expected to be between certain dates.
new tab
<vaadin-date-time-picker
label="Meeting date and time"
.initialPosition="${startOfNextMonthISOString}"
></vaadin-date-time-picker>
Internationalization (i18n)
Date Time Picker allows localizing texts and labels, such as month names and button labels.
new tab
@query('vaadin-date-time-picker')
private dateTimePicker!: DateTimePicker;
protected override firstUpdated() {
this.dateTimePicker.i18n = {
...this.dateTimePicker.i18n,
monthNames: [
'Januar',
'Februar',
'März',
'April',
'Mai',
'Juni',
'Juli',
'August',
'September',
'Oktober',
'November',
'Dezember',
],
weekdays: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
weekdaysShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
today: 'Heute',
cancel: 'Abbrechen',
dateLabel: 'datum',
timeLabel: 'zeit',
};
}
protected override render() {
return html`<vaadin-date-time-picker label="Sitzungsdatum"></vaadin-date-time-picker>`;
}
See also how to configure a custom date format.
Basic Features
The following features, common to most input field components, are supported:
Label
The label is used to identify the input field. It supports plain-text content, and its length is limited to the width of the field. Helpers and Tooltips can be used to provide additional information that doesn’t fit into the label.
Visible labels are strongly recommended for all input fields. In cases where the built-in label cannot be used, an external element can be associated as the field’s label through the aria-labelledby
attribute. Fields without any visible label should include an invisible label for assistive technologies with the aria-label
attribute.
Helper
Helpers are used to provide additional information that the user may need to enter in the field, such as format requirements or explanations of the field’s purpose below the field.
A style variant is available for rendering the helper above the field.
In addition to plain text, helpers can contain components and HTML elements. However, complex and interactive content is likely to have accessibility issues.
Placeholder
The placeholder is text that’s displayed when the field is empty. Its primary purpose is to provide a short input hint (e.g., the expected format) in situations where a Helper cannot be used.
Placeholders should not be used as a replacement for a visible label. They can be mistaken for a manually entered value. See Label for alternatives to the built-in field label.
Tooltip
Tooltips are small text pop-ups displayed on hover, and on keyboard-focus. They can be used to provide additional information about a field. This can be useful in situations where an always visible Helper is not appropriate. Helpers are generally recommended in favor of tooltips, though, as they provide much better discoverability and mobile support. See the Tooltip documentation for more information.
Invisible Labels (ARIA)
If the built-in label cannot be used, an invisible label should be provided for users of assistive technologies like screen readers. The date and time sub-fields can also be assigned invisible suffixes (e.g., date
and time
) that are appended to their invisible labels.
<!-- Invisible label for screen readers: -->
<date-time-picker accessible-name="Meeting">...
<!-- Suffixes for date and time sub-fields are set through the i18n object -->
new tab
<vaadin-date-time-picker
label="Label"
helper-text="Helper text"
date-placeholder="Date"
time-placeholder="Time"
>
<vaadin-tooltip slot="tooltip" text="Tooltip text"></vaadin-tooltip>
</vaadin-date-time-picker>
Read-Only & Disabled
Fields used to display values should be set to read-only
mode to prevent editing. Read-only fields are focusable and visible to screen readers. They can display tooltips. Their values can be selected and copied.
Fields that are currently unavailable should be disabled
. The reduced contrast of disabled fields makes them inappropriate for displaying information. They can’t be focused or display tooltips. They’re invisible to screen readers, and their values cannot be selected and copied.
Disabled fields can be useful in situations where they can become enabled based on some user action. Consider hiding fields entirely if there’s nothing the user can do to make them editable.
new tab
<vaadin-date-time-picker readonly label="Read-only" value="2020-06-12T12:30">
</vaadin-date-time-picker>
<vaadin-date-time-picker disabled label="Disabled"></vaadin-date-time-picker>
Style Variants
The following style variants can be applied:
Text Alignment
Three different text alignments are supported: left
, which is the default; center
; and right
.
Right-alignment is recommended for numerical values when presented in vertical groups. This tends to aid interpretation and comparison of values.
Small Variant
The small variant can be used to make individual fields more compact. The default size of fields can be customized with style properties.
Helper Above Field
The helper can be rendered above the field, and below the label.
Borders
Borders can be applied to the field surface by providing a value (e.g., 1px
) to the --vaadin-input-field-border-width
CSS property. This can be applied globally to all input fields using the html
selector, or to individual component instances. Borders are required to achieve WCAG 2.1 level AA conformant color contrast with the default Lumo styling of fields.
You can override the default border color with the --vaadin-input-field-border-color
property.
new tab
<vaadin-date-time-picker
theme="align-right small helper-above-field"
label="Label"
helper-text="Helper text"
value="2020-06-12T12:30"
style="--vaadin-input-field-border-width: 1px;"
></vaadin-date-time-picker>
Usage Patterns
Date Time Range
You can accomplish a date time range picker using two Date Time Pickers.
new tab
<div>
<vaadin-date-time-picker
label="Start date and time"
.value="${this.startDateTime}"
@value-changed="${(event: DateTimePickerValueChangedEvent) => {
this.startDateTime = event.detail.value;
}}"
></vaadin-date-time-picker>
<vaadin-date-time-picker
label="End date and time"
.min="${this.startDateTime}"
.value="${this.endDateTime}"
@value-changed="${(event: DateTimePickerValueChangedEvent) => {
this.endDateTime = event.detail.value;
}}"
></vaadin-date-time-picker>
</div>
To disable the days before the start date in the end date picker, you need to handle the selection in the start date picker and change the range in the end date picker.
Best Practices
Use Date Time Picker when the user needs to choose both a date and time of day. If you only need a date or time of day, use Date Picker or Time Picker, respectively.
Picking vs. Typing
The calendar overlay is useful when the user needs to choose a day that’s close to the current date or when information such as day of the week, week number, valid dates, and so on, can aid in choosing the best option.
For far off dates (i.e., years ago or years from now) and for known dates (i.e., holidays and birthdays), typing the date can be a faster and easier approach. It’s important to verify that the user can enter dates according to their locale.
Providing Input Guidance
Use a helper text to show the expected date and time formats, and placeholders to help users identify the two sub-fields, correctly.
new tab
<vaadin-date-time-picker
label="Select date and time"
helper-text="Format: DD/MM/YYYY and HH:MM"
date-placeholder="Date"
time-placeholder="Time"
></vaadin-date-time-picker>