# Blazor DatePicker, TimePicker and Calendar

URL: https://flexcoreui.com/demo/date-time  
Section: Components  
Controls: DatePickerControl, TimePickerControl, DateRangePickerControl, CalendarControl, TimeSpanPickerControl  
Keywords: date picker, datepicker, time picker, date range picker, calendar, timespan picker

Blazor date, time, range, calendar and duration pickers: users type a date in any of sixteen formats or pick it from a calendar.

## Documentation

### Date picker

| Name | Type | Default | Description |
|---|---|---|---|
| Value | DateTime? | null | Selected date, or date and time with ShowTime. Two-way with @bind-Value. |
| ValueChanged | EventCallback<DateTime?> |  | Fires when typed text parses (Enter or blur) or a day is picked. |
| ValueExpression | Expression<Func<DateTime?>>? | null | Set by @bind-Value, but the date picker never reads it: it reports nothing to an EditContext. |
| Format | string? | "MM/dd/yyyy" (with time: "MM/dd/yyyy hh:mm tt") | Display format. Typed text is tried against this first, then the built-in list. |
| Placeholder | string? | the format | Input placeholder. |
| ShowTime | bool | false | Adds a time box to the drop-down and time formats to parsing. |
| MinDate / MaxDate | DateTime? | null | Days outside are disabled in the calendar. A typed date outside is not refused: the bound value moves to the nearest bound, but the box keeps showing the typed date. The time picker refuses its own. |
| ShowCalendarSidebar | bool | false | Expandable sidebar of shortcuts: Today, Yesterday, Tomorrow, Start and End of Week, Next Week, Start and End of Month, Clear Date. |
| ParseFormats | IEnumerable<string>? | null | Extra formats tried before the sixteen built-in ones (ISO, US, day-month, dd-MMM-yy, digit runs). |
| Culture | CultureInfo? | invariant | Formatting and parsing culture; null uses the invariant culture (typed text also falls back to the current culture). Month names in the drop-down follow the current culture. |
| ShowTriggerButton | bool | true | Shows the 📅 button. Without it Enter on an empty field no longer opens the calendar. |
| OpenCalendarOnDoubleClick | bool | false | Double-click in the input opens the calendar. |
| AutoFocus | bool | false | Focuses the input once after first render. |
| AriaLabel | string? | null | Accessible name of the input. |
| ValidationChanged | EventCallback<string?> |  | Fires with the parse message, or null when the text is valid again. |
| Enabled / Visible / Id / CssClass / Style (base) |  |  | All honored on the host. |
| Grid-cell hosting |  |  | OpenOnRender, InitialText, Uncontrolled, InputValueChanged, ElementReferenceCaptured, OnKeyDown, CalendarButtonKeyDown serve the grid's cell editor; see the source comments before using them in a form. |

### Time picker

| Name | Type | Default | Description |
|---|---|---|---|
| Value | TimeOnly? | null | Selected time. Two-way with @bind-Value. |
| ValueChanged | EventCallback<TimeOnly?> |  | Fires when a list entry is chosen or typed text parses on Enter or on leaving the box. |
| ValueExpression | Expression<Func<TimeOnly?>>? | null | Set by @bind-Value; validation messages go to the EditContext. |
| Min / Max | TimeOnly | 00:00 / 23:59:59.9999999 | First and last entry; typed times outside are refused. |
| Step | TimeSpan | 30 minutes | Gap between entries. At least one second, and at most 1441 entries, or the control throws. |
| Format | string | "hh:mm tt" | Display and parse format; text in another layout is also tried with the culture's parser. |
| Culture | CultureInfo | current | Formatting culture. |
| Width | string? | null | CSS width of the drop-down. |
| AriaLabel | string? | null | Accessible name of the input. |
| ValidationChanged | EventCallback<string?> |  | Fires with the error text, or null once valid. |
| OnKeyDown | EventCallback<KeyboardEventArgs> |  | Raw key events from the input. |
| Enabled / Visible (base) | bool | true | Honored. |

### Range picker

| Name | Type | Default | Description |
|---|---|---|---|
| Value | CalendarRange | (null, null) | Start and end; either may be null. Two-way with @bind-Value. |
| ValueChanged | EventCallback<CalendarRange> |  | Fires after either picker or the popup calendar changes the range, even when it is invalid. |
| ValueExpression | Expression<Func<CalendarRange>>? | null | Set by @bind-Value; the error goes to the EditContext. |
| Min / Max | DateTime? | null | Bounds for both dates. Min after Max throws. |
| DisabledDate | Func<DateTime,bool>? | null | Days that cannot be inside the range, the start and end days included. |
| AriaLabel | string | "Date range" | Accessible name of the group. |
| Enabled (base) | bool | true | false disables the pickers and the Choose range button. |

### Calendar rows

| Name | Type | Default | Description |
|---|---|---|---|
| Value / ValueChanged | DateTime? | null | Selection in Single mode. |
| Values / ValuesChanged | IReadOnlyList<DateTime> | empty | Selection in Multiple mode; a click toggles the day and the list is kept sorted. |
| Range / RangeChanged | CalendarRange | (null, null) | Selection in Range mode: first click sets the start, second the end; a click before the start swaps them. |
| SelectionMode | CalendarSelectionMode | Single | Single, Multiple or Range. |
| Min / Max | DateTime? | null | Days outside are disabled and the month buttons stop there. |
| DisabledDate | Func<DateTime,bool>? | null | Extra disabled days. A range that would cross one is refused. |
| Culture | CultureInfo | current | Day names, month names and the default first day. |
| FirstDayOfWeek | DayOfWeek? | null | Overrides the culture's first day. |
| DisplayDate / DisplayDateChanged | DateTime? | value or today | Month on show. Changes when the user navigates. |
| View / ViewChanged | CalendarView | Month | Month, Year (pick a month) or Decade (pick a year). The heading button cycles them. |
| ShowTodayButton | bool | true | Renders a Today button under the grid. |
| DayTemplate | RenderFragment<CalendarCellContext>? | null | Custom day cell; receives CalendarCellContext. |
| Enabled / Visible / Id (base) |  |  | Honored. |

### Duration

| Name | Type | Default | Description |
|---|---|---|---|
| Value | TimeSpan? | null | Duration. Two-way with @bind-Value; null shows zeros. |
| ValueChanged | EventCallback<TimeSpan?> |  | Fires when a box commits (blur or Enter), not per keystroke. |
| ShowDays | bool | false | Adds a days box (0 or more). |
| ShowSeconds | bool | false | Adds a seconds box (0–59). |
| Disabled | bool | false | Disables the boxes. The base Enabled and Visible are not read by this control. |
| (unmatched attributes) | Dictionary<string,object> |  | Forwarded to the host <div>. |

### Records

| Name | Type | Description |
|---|---|---|
| CalendarRange.Start / End | DateTime? | Either bound may be null. Positional record: new(start, end), update with with. |
| CalendarCellContext | record | Date, Selected, Disabled, InCurrentMonth: what a DayTemplate receives. |

### Methods

| Name | Type | Description |
|---|---|---|
| DatePickerControl.FocusAsync() | Task | Focuses the input. |
| TimePickerControl.FocusAsync() | Task | Focuses the drop-down's input. |
| TimePickerControl.ErrorMessage | string? | Current parse or bounds message, or null. |
| DateRangePickerControl.SetValueAsync(range) | Task | Validates order, bounds and disabled days, publishes the error and raises ValueChanged. |
| DateRangePickerControl.Error | string? | Current message, or null. |
| CalendarControl.NavigateAsync(direction) | Task | Moves one period back (−1) or forward (+1) in the current view. |
| CalendarControl.SelectAsync(date) | Task | Same as clicking the day: honors the selection mode and disabled days. |

### Css

| Name | Description |
|---|---|
| fx-datepicker-host · -input-group · -input · -trigger | Host, the input row, the text box and the 📅 button. -input-group-no-trigger when the button is hidden. |
| fx-datepicker-dropdown · -popup-layer · -backdrop · -validation-pill | The calendar (expanded or minimal with the sidebar), its top-layer wrapper, the click-away backdrop and the error pill. |
| fx-calendar-main · fx-calendar-sidebar · fx-shortcut-btn | Drop-down month panel, shortcut sidebar and its buttons. |
| fx-timepicker · fx-timepicker-error | Host around the drop-down list and the error line. |
| fx-date-range · fx-range-error | Flex row of the two pickers, the Choose range button and the error. |
| fx-calendar · -header · -cells · -row · -cell | Standalone calendar; cells take selected, today and outside. |
| fx-timespan-picker · -segment · -input · -unit | Bordered row of number boxes with unit letters; disabled grays it. |

### Vars

| Name | Type | Description |
|---|---|---|
| --fx-border · --fx-surface · --fx-text · --fx-primary | #cbd5e1 · #fff · #202630 · #2563eb | Read by CalendarControl for its frame, background, text and the selected day. |
| --fx-zoom | 1 | Scales the date picker's drop-down. |
| (none) | — | The range and time span pickers' own stylesheets read none, and the time picker has none. Their inner controls do: the range popup is a CalendarControl, and the time list is a DropDownListControl, which reads --fx-zoom. |

### Date keys

| Name | Description |
|---|---|
| F4 / Alt+Arrow Down | Open or close the calendar. |
| Enter | Parse the typed text. On an empty field, open the calendar instead. |
| Escape | Close the calendar; typed text stays for correction. |
| Arrow keys (calendar open) | Left and Right move a day, Up and Down a week. |
| Page Up / Page Down | Previous or next month; with Shift, a year. |
| Home / End | First or last day of the focused week. |
| Enter / Space (calendar open) | Select the focused day. |

### Calendar keys

| Name | Description |
|---|---|
| Arrow keys | Move the focused day; disabled days are skipped and the month follows. |
| Page Up / Page Down | Same day in the previous or next month; with Shift, year. |
| Home / End | First or last day of the week, honoring FirstDayOfWeek. |
| Enter / Space | Select the focused day (a native button). |

## Examples

### Appointment

```razor
@using Fx.ControlKit

<div class="dt">
    <div class="fields">
        <div class="field"><span class="field-label">Pickup date</span><DatePickerControl @bind-Value="_date" MinDate="TripStart" MaxDate="TripEnd" ShowCalendarSidebar="true" AriaLabel="Pickup date" /></div>
        <div class="field"><span class="field-label">Pickup time</span><TimePickerControl @bind-Value="_time" Min="@(new TimeOnly(6, 0))" Max="@(new TimeOnly(22, 0))" Width="150px" AriaLabel="Pickup time" /></div>
        <div class="field"><span class="field-label" id="car-needed-title">Car needed for</span><TimeSpanPickerControl @bind-Value="_duration" role="group" aria-labelledby="car-needed-title" /></div>
    </div>
    <p class="result" role="status">@Transfer</p>
</div>
```

```csharp
// Transfer
private static DateTime TripStart => DateTime.Today.AddDays(7);
private static DateTime TripEnd => DateTime.Today.AddDays(11);
private DateTime? _date = TripStart;
private TimeOnly? _time = new(9, 30);
private TimeSpan? _duration = TimeSpan.FromMinutes(90);
private string Transfer => _date is { } d && _time is { } t
    ? $"Car for Albus Door, Lisbon airport to the old town: {d:ddd MMM d}, {t:h:mm tt} to {t.Add(_duration ?? TimeSpan.Zero):h:mm tt}. The trip runs {TripStart:MMM d} to {TripEnd:MMM d}."
    : "Pick a pickup date and time.";
```

### Range

```razor
@using Fx.ControlKit

<div class="dt">
    <div class="fields">
        <DateRangePickerControl @ref="_picker" @bind-Value="_stay" Min="DateTime.Today" Max="DateTime.Today.AddDays(180)" DisabledDate="SoldOut" AriaLabel="Stay dates" />
        <ButtonControl CssClass="btn-sm" OnClick="@(() => Preset(LongWeekend, 3))">Long weekend</ButtonControl>
        <ButtonControl CssClass="btn-sm" OnClick="@(() => Preset(FirstOpen, 7))">One week</ButtonControl>
    </div>
    <p class="result" role="status">@Stay</p>
</div>
```

```csharp
// Date range
private static DateTime FirstOpen => DateTime.Today.AddDays(14);
// A long weekend starts on the first Friday from FirstOpen on.
private static DateTime LongWeekend => FirstOpen.AddDays(((int)DayOfWeek.Friday - (int)FirstOpen.DayOfWeek + 7) % 7);
private DateRangePickerControl? _picker;
private CalendarRange _stay = new(FirstOpen, FirstOpen.AddDays(3));
// Three dates next week are sold out: no stay can include them, not even as its check-out day.
private static bool SoldOut(DateTime day) => day >= DateTime.Today.AddDays(8) && day <= DateTime.Today.AddDays(10);
private Task Preset(DateTime start, int nights) => _picker!.SetValueAsync(new(start, start.AddDays(nights)));
// Error is set before ValueChanged, so a typed range across a sold-out date gets no quote.
private string Stay => _picker?.Error is { } error
    ? $"No quote. {error}"
    : _stay is { Start: { } s, End: { } e } && e >= s
    ? $"Amalfi hotel for Albus Door: {(e - s).Days} night{((e - s).Days == 1 ? "" : "s")}, {s:ddd MMM d} to {e:ddd MMM d}, {((e - s).Days * 180).ToString("C0")} at $180 a night. {DateTime.Today.AddDays(8):MMM d} to {DateTime.Today.AddDays(10):MMM d} is sold out."
    : "Pick a check-in and a check-out date.";
```

### Calendar

```razor
@using Fx.ControlKit

<div class="dt">
    <div class="cal-row">
        <CalendarControl @bind-Values="_departures" SelectionMode="CalendarSelectionMode.Multiple" Min="DateTime.Today" Max="DateTime.Today.AddDays(90)"
                         DisabledDate="NoDeparture" FirstDayOfWeek="DayOfWeek.Monday">
            <DayTemplate Context="day">
                <span class="day">@day.Date.Day</span>
                @if (!day.Disabled && day.InCurrentMonth) { <span class="day-price">$@Price(day.Date)</span> }
            </DayTemplate>
        </CalendarControl>
        <p class="result departures" role="status">@Departures</p>
    </div>
</div>
```

```csharp
// Calendar
private IReadOnlyList<DateTime> _departures = new[] { NextDeparture(1), NextDeparture(4) };
// The Kyoto garden tour does not leave on Mondays; weekend departures cost more.
private static bool NoDeparture(DateTime d) => d.DayOfWeek == DayOfWeek.Monday;
private static int Price(DateTime d) => d.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday ? 95 : 80;
private static DateTime NextDeparture(int daysAhead)
{
    var d = DateTime.Today.AddDays(daysAhead);
    return NoDeparture(d) ? d.AddDays(1) : d;
}
private string Departures => _departures.Count == 0
    ? "No departures picked."
    : $"{_departures.Count} departure{(_departures.Count == 1 ? "" : "s")}: {string.Join(", ", _departures.OrderBy(d => d).Select(d => $"{d:ddd MMM d} (${Price(d)})"))}. Cheapest: ${_departures.Min(Price)}.";
```

