> Markdown version of [Date Time Picker](https://vaadin.com/docs/v23/components/date-time-picker). Section index: [llms.txt](https://vaadin.com/docs/v23/components/llms.txt)

# Date Time Picker

Date Time Picker is an input field for selecting both a date and a time.

**TypeScript** — `date-time-picker-basic.ts`

```html
<vaadin-date-time-picker label="Meeting date and time"></vaadin-date-time-picker>
```

**Java** — `DateTimePickerBasic.java`

```java
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.

## <a id="common-input-field-features"></a>Common Input Field Features

Date Time Picker includes all Text Field and shared input field features.

- [See Text Field features](https://vaadin.com/docs/v23/components/text-field.md)

- [See shared input field features](https://vaadin.com/docs/v23/components/input-fields.md)

## <a id="step"></a>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/decreases using the up/down arrow keys (when the overlays are disabled).

The default step is one hour (that is, `3600`). Unlike with [Number Field](https://vaadin.com/docs/v23/components/number-field.md), Date Time Picker accepts values that don’t align with the specified step.

**TypeScript** — `date-time-picker-minutes-step.ts`

```html
<vaadin-date-time-picker
  label="Meeting date and time"
  value="2020-06-12T12:30"
  .step="${60 * 30}"
></vaadin-date-time-picker>
```

**Java** — `DateTimePickerMinutesStep.java`

```java
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 an hour or day evenly. 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.

**TypeScript** — `date-time-picker-seconds-step.ts`

```html
<vaadin-date-time-picker
  label="Message received"
  value="2020-06-12T15:45:08"
  step="1"
></vaadin-date-time-picker>
```

**Java** — `DateTimePickerSecondsStep.java`

```java
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);
```

<!-- vale Vaadin.Abbr = NO -->

| Step                 | Format       |
| -------------------- | ------------ |
| Less than 60 seconds | HH:MM:SS     |
| Less than 1 second   | HH:MM:SS:FFF |

<!-- vale Vaadin.Abbr = YES -->

> **Note: Limit the number of steps**
>
> The overlay doesn’t appear for steps less than 900 seconds (15 minutes) to avoid showing an impractical number of choices.

## <a id="auto-open"></a>Auto Open

The overlay opens automatically when the field is focused using a pointer (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 up/down arrow keys are pressed.

**TypeScript** — `date-time-picker-auto-open.ts`

```html
<vaadin-date-time-picker
  label="Meeting date and time"
  auto-open-disabled
></vaadin-date-time-picker>
```

**Java** — `DateTimePickerAutoOpen.java`

```java
dateTimePicker.setAutoOpen(false);
```

## <a id="validation"></a>Validation

### <a id="min-and-max-values"></a>Min and Max Values

You can define a `min` and `max` value for Date Time Picker if you need to restrict the input to a specific range:

**TypeScript** — `date-time-picker-min-max.ts`

```html
<vaadin-date-time-picker
  label="Appointment date and time"
  helper-text="Must be within 60 days from today"
  .value="${format(this.initialValue, dateTimeFormat)}"
  .min="${format(this.minDate, dateTimeFormat)}"
  .max="${format(this.maxDate, dateTimeFormat)}"
  .errorMessage="${this.errorMessage}"
  @change="${({ target }: DateTimePickerChangeEvent) => {
    const date = parseISO(target.value ?? '');
    if (isBefore(date, this.minDate)) {
      this.errorMessage = 'Too early, choose another date and time';
    } else if (isAfter(date, this.maxDate)) {
      this.errorMessage = 'Too late, choose another date and time';
    } else {
      this.errorMessage = '';
    }
  }}"
></vaadin-date-time-picker>
```

**Java** — `DateTimePickerMinMax.java`

```java
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setLabel("Appointment date and time");
dateTimePicker.setHelperText("Must be within 60 days from today");
dateTimePicker.setAutoOpen(true);
dateTimePicker.setMin(LocalDateTime.now());
dateTimePicker.setMax(LocalDateTime.now().plusDays(60));
dateTimePicker.setValue(LocalDateTime.now().plusDays(7));
dateTimePicker.addValueChangeListener(event -> {
    LocalDateTime value = event.getValue();
    String errorMessage = null;
    if (value != null) {
        if (value.compareTo(dateTimePicker.getMin()) < 0) {
            errorMessage = "Too early, choose another date and time";
        } else if (value.compareTo(dateTimePicker.getMax()) > 0) {
            errorMessage = "Too late, choose another date and time";
        }
    }
    dateTimePicker.setErrorMessage(errorMessage);
});
add(dateTimePicker);
```

### <a id="custom-validation"></a>Custom Validation

If the `min` and `max` values aren’t enough, you can also apply custom validation.

**TypeScript** — `date-time-picker-custom-validation.ts`

```html
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>
  `;
}
```

**Java** — `DateTimePickerCustomValidation.java`

```java
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));
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);
```

## <a id="week-numbers"></a>Week Numbers

You can configure Date Time Picker to show week numbers in the date picker overlay.

**TypeScript** — `date-time-picker-week-numbers.ts`

```html
@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>
  `;
}
```

**Java** — `DateTimePickerWeekNumbers.java`

```java
dateTimePicker.setWeekNumbersVisible(true);
dateTimePicker.setDatePickerI18n(
        new DatePicker.DatePickerI18n().setFirstDayOfWeek(1));
```

The week numbers are displayed according to [ISO-8601](https://www.iso.org/iso-8601-date-and-time-format.html). They can only be displayed when the first day of the week is Monday.

## <a id="initial-position"></a>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 and/or scrolling when the user’s input is expected to be between certain dates.

**TypeScript** — `date-time-picker-initial-position.ts`

```html
<vaadin-date-time-picker
  label="Meeting date and time"
  .initialPosition="${startOfNextMonthISOString}"
></vaadin-date-time-picker>
```

**Java** — `DateTimePickerInitialPosition.java`

```java
// 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);
```

## <a id="internationalization-i18n"></a>Internationalization (i18n)

Date Time Picker allows localizing texts and labels, such as month names and button labels.

**TypeScript** — `date-time-picker-internationalization.ts`

```typescript
@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'],
    week: 'Woche',
    today: 'Heute',
    cancel: 'Abbrechen',
  };
}

protected override render() {
  return html`<vaadin-date-time-picker label="Sitzungsdatum"></vaadin-date-time-picker>`;
}
```

**Java** — `DateTimePickerInternationalization.java`

```java
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.setWeek("Woche");
germanI18n.setToday("Heute");
germanI18n.setCancel("Abbrechen");

dateTimePicker.setDatePickerI18n(germanI18n);
```

See also how to [configure a custom date format](https://vaadin.com/docs/v23/components/date-picker.md#date-format).

## <a id="usage-patterns"></a>Usage Patterns

### <a id="date-time-range"></a>Date Time Range

You can accomplish a date time range picker using two Date Time Pickers.

**TypeScript** — `date-time-picker-range.ts`

```html
<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>
```

**Java** — `DateTimePickerRange.java`

```java
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.

## <a id="best-practices"></a>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](https://vaadin.com/docs/v23/components/date-picker.md) or [Time Picker](https://vaadin.com/docs/v23/components/time-picker.md) respectively.

### <a id="picking-vs-typing"></a>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 days well into the past or future, and for known dates such as 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.

### <a id="providing-input-guidance"></a>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.

**TypeScript** — `date-time-picker-input-format.ts`

```html
<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>
```

**Java** — `DateTimePickerInputFormat.java`

```java
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);
```

## <a id="related-components"></a>Related Components

| Component                                                            | Usage recommendations                                  |
| -------------------------------------------------------------------- | ------------------------------------------------------ |
| [Time Picker](https://vaadin.com/docs/v23/components/time-picker.md) | Input field for entering or selecting a specific time. |
| [Date Picker](https://vaadin.com/docs/v23/components/date-picker.md) | Input field for entering or selecting a specific date. |

`58305ABE-B962-4ED0-A1C7-36BB906C9452`
