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.
new tab
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Meeting date and time");
add(dateTimePicker);
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
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Meeting date and time");
dateTimePicker.setStep(Duration.ofMinutes(30));
dateTimePicker.setValue(LocalDateTime.of(2020, 6, 12, 12, 30, 0));
add(dateTimePicker);
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
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Message received");
dateTimePicker.setStep(Duration.ofSeconds(1));
dateTimePicker.setValue(LocalDateTime.of(2020, 6, 12, 15, 45, 8));
add(dateTimePicker);
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.
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
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setRequiredIndicatorVisible(true);
dateTimePicker.setLabel("Appointment date and time");
dateTimePicker.setHelperText("Must be within 60 days from today");
dateTimePicker.setMin(LocalDateTime.now());
dateTimePicker.setMax(LocalDateTime.now().plusDays(60));
dateTimePicker.setI18n(new DateTimePickerI18n()
.setRequiredErrorMessage("Field is required")
.setBadInputErrorMessage("Invalid date or time format")
.setMinErrorMessage("Too early, choose another date and time")
.setMaxErrorMessage("Too late, choose another date and time"));
add(dateTimePicker);
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
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Appointment date and time");
dateTimePicker
.setHelperText("Open Mondays-Fridays, 8:00-12:00, 13:00-16:00");
dateTimePicker.setStep(Duration.ofMinutes(30));
dateTimePicker.setI18n(new DateTimePickerI18n()
.setBadInputErrorMessage("Invalid date or time format"));
add(dateTimePicker);
String errorMessage = "The selected day of week or time is not available";
Binder<Appointment> binder = new Binder<>(Appointment.class);
binder.forField(dateTimePicker).withValidator(startDateTime -> {
boolean validWeekDay = startDateTime.getDayOfWeek().getValue() >= 1
&& startDateTime.getDayOfWeek().getValue() <= 5;
return validWeekDay;
}, errorMessage).withValidator(startDateTime -> {
LocalTime startTime = LocalTime.of(startDateTime.getHour(),
startDateTime.getMinute());
boolean validTime = !(LocalTime.of(8, 0).isAfter(startTime)
|| (LocalTime.of(12, 0).isBefore(startTime)
&& LocalTime.of(13, 0).isAfter(startTime))
|| LocalTime.of(16, 0).isBefore(startTime));
return validTime;
}, errorMessage).bind(Appointment::getStartDateTime,
Appointment::setStartDateTime);
Week Numbers
You can configure Date Time Picker to show week numbers in the date picker overlay.
new tab
dateTimePicker.setWeekNumbersVisible(true);
dateTimePicker.setDatePickerI18n(
new DatePicker.DatePickerI18n().setFirstDayOfWeek(1));
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
// https://github.com/vaadin/vaadin-date-time-picker/issues/57
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
LocalDate startOfNextMonth = LocalDate.now(ZoneId.systemDefault())
.with(TemporalAdjusters.firstDayOfNextMonth());
String startOfNextMonthIsoString = formatter.format(startOfNextMonth);
dateTimePicker.getElement().executeJs("this.initialPosition = $0",
startOfNextMonthIsoString);
Internationalization (i18n)
Date Time Picker allows localizing texts and labels, such as month names and button labels.
new tab
DatePicker.DatePickerI18n germanI18n = new DatePicker.DatePickerI18n();
germanI18n.setMonthNames(List.of("Januar", "Februar", "März", "April",
"Mai", "Juni", "Juli", "August", "September", "Oktober",
"November", "Dezember"));
germanI18n.setWeekdays(List.of("Sonntag", "Montag", "Dienstag",
"Mittwoch", "Donnerstag", "Freitag", "Samstag"));
germanI18n.setWeekdaysShort(
List.of("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"));
germanI18n.setToday("Heute");
germanI18n.setCancel("Abbrechen");
dateTimePicker.setDatePickerI18n(germanI18n);
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
DateTimePicker field = new DateTimePicker();
field.setLabel("Label");
field.setHelperText("Helper text");
field.setDatePlaceholder("Date");
field.setTimePlaceholder("Time");
field.setTooltipText("Tooltip text");
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
DateTimePicker readonlyField = new DateTimePicker();
readonlyField.setReadOnly(true);
readonlyField.setLabel("Read-only");
readonlyField.setValue(LocalDateTime.of(2020, 6, 12, 12, 30));
DateTimePicker disabledField = new DateTimePicker();
disabledField.setEnabled(false);
disabledField.setLabel("Disabled");
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
DateTimePicker field = new DateTimePicker();
field.addThemeVariants(DateTimePickerVariant.LUMO_SMALL,
DateTimePickerVariant.LUMO_ALIGN_RIGHT,
DateTimePickerVariant.LUMO_HELPER_ABOVE_FIELD);
field.getStyle().set("--vaadin-input-field-border-width", "1px");
Usage Patterns
Date Time Range
You can accomplish a date time range picker using two Date Time Pickers.
new tab
DateTimePicker startDateTimePicker = new DateTimePicker(
"Start date and time");
startDateTimePicker.setValue(LocalDateTime.of(2020, 8, 25, 20, 0, 0));
DateTimePicker endDateTimePicker = new DateTimePicker(
"End date and time");
endDateTimePicker.setValue(LocalDateTime.of(2020, 9, 1, 20, 0, 0));
startDateTimePicker.addValueChangeListener(
e -> endDateTimePicker.setMin(e.getValue()));
add(startDateTimePicker, endDateTimePicker);
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
DatePickerI18n dateFormat = new DatePickerI18n();
dateFormat.setDateFormat("dd/MM/yyyy");
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Select date and time");
dateTimePicker.setDatePickerI18n(dateFormat);
dateTimePicker.setHelperText("Format: DD/MM/YYYY and HH:MM");
dateTimePicker.setDatePlaceholder("Date");
dateTimePicker.setTimePlaceholder("Time");
add(dateTimePicker);