# Date range picker

> Two native date controls with a shared label and validation for an end date earlier than the start.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/date-range-picker`
- File: `src/components/haze/ui/date-range-picker.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/date-range-picker

## Use when
- A report or export collects a start date and an end date
- Native date pickers suit the device and locale

## Avoid when
- Only one date is needed. Use input with type date.
- Customers need a visual overview of unavailable dates throughout a calendar.

## Alternatives
- [input](https://hazeui.com/ui/input.md)
- [field](https://hazeui.com/ui/field.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique prefix for both field IDs and the validation message. |
| label | `string` | "Date range" | no | Legend for the pair. |
| start | `string` |  | no | Initial start date in YYYY-MM-DD format. |
| end | `string` |  | no | Initial end date in YYYY-MM-DD format. |
| startName | `string` | id + -start | no | Submitted name for the start date. |
| endName | `string` | id + -end | no | Submitted name for the end date. |
| startLabel | `string` | "Start" | no | Start field label. |
| endLabel | `string` | "End" | no | End field label. |
| min | `string` |  | no | Earliest date for either field. |
| max | `string` |  | no | Latest date for either field. |
| required | `boolean` |  | no | Requires both dates. |
| disabled | `boolean` |  | no | Disables both fields. |
| orderError | `string` | "Choose an end date on or after the start date." | no | Validation text for a reversed range. |
| startAttributes | `Record<string, unknown>` |  | no | Additional attributes for the start input. |
| endAttributes | `Record<string, unknown>` |  | no | Additional attributes for the end input. |
| class | `string` |  | no | Additional classes on the fieldset. |

## Accessibility
- The fieldset legend and each input label describe the two levels of the control.
- The browser controls how each date picker opens and displays dates.
- Validate the date order on the server as well. Without JavaScript both fields still submit.
- Key Tab: Move between the date fields and their native controls.

## Agent prompts

### Install and use

Install the Haze UI component "Date range picker" with `npx shadcn@latest add @haze/date-range-picker`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import DateRangePicker from "@/components/haze/ui/date-range-picker.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/date-range-picker.md

### Customize with real content

Adapt the Haze date-range-picker ui for our product. Replace the demo values of these props with our real content: id, label, start, end, startName, endName, startLabel, endLabel, min, max, required, disabled, orderError, startAttributes, endAttributes, class. Keep the layout, the heading level rules and these accessibility details: The fieldset legend and each input label describe the two levels of the control. The browser controls how each date picker opens and displays dates. Validate the date order on the server as well. Without JavaScript both fields still submit. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using date-range-picker, check it fits: use it when a report or export collects a start date and an end date; native date pickers suit the device and locale. Avoid it when only one date is needed. use input with type date.; customers need a visual overview of unavailable dates throughout a calendar.. Alternatives: @haze/input, @haze/field.

## Example requests that should lead here
- Add a reporting period picker that submits from and through dates and flags reversed ranges.

## Source

```astro
---
import { CalendarRange, ChevronLeft, ChevronRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Input from "./input.astro";

interface Props {
  id: string;
  label?: string;
  start?: string;
  end?: string;
  startName?: string;
  endName?: string;
  startLabel?: string;
  endLabel?: string;
  min?: string;
  max?: string;
  required?: boolean;
  disabled?: boolean;
  locale?: string;
  weekStart?: 0 | 1;
  orderError?: string;
  startAttributes?: Record<string, unknown>;
  endAttributes?: Record<string, unknown>;
  class?: string;
}

const {
  id,
  label = "Date range",
  start,
  end,
  startName = `${id}-start`,
  endName = `${id}-end`,
  startLabel = "Start",
  endLabel = "End",
  min,
  max,
  required,
  disabled,
  locale = "en",
  weekStart = 1,
  orderError = "Choose an end date on or after the start date.",
  startAttributes,
  endAttributes,
  class: className,
} = Astro.props;

const { "aria-describedby": endDescription, ...endRest } = endAttributes ?? {};
const endDescribedBy = [endDescription, `${id}-order`].filter(Boolean).join(" ");
const panelId = `${id}-range-popover`;
---

<fieldset
  disabled={disabled}
  data-haze-date-range-picker
  data-locale={locale}
  data-week-start={weekStart}
  data-order-error={orderError}
  class={cn("min-w-0", className)}
>
  <legend class="mb-3 text-[0.8125rem]/5 font-medium text-foreground">{label}</legend>
  <div class="grid min-w-0 gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] sm:items-end" style={`anchor-name: --${panelId}`}>
    <div class="grid min-w-0 gap-2">
      <label for={`${id}-start`} class="text-[0.8125rem]/5 font-medium text-foreground">{startLabel}</label>
      <Input
        {...startAttributes}
        id={`${id}-start`}
        name={startName}
        type="date"
        value={start}
        min={min}
        max={max}
        required={required}
        data-start
        class="[[data-haze-date-range-picker][data-enhanced]_&]:[&::-webkit-calendar-picker-indicator]:hidden"
      />
    </div>
    <div class="grid min-w-0 gap-2">
      <label for={`${id}-end`} class="text-[0.8125rem]/5 font-medium text-foreground">{endLabel}</label>
      <Input
        {...endRest}
        id={`${id}-end`}
        name={endName}
        type="date"
        value={end}
        min={min}
        max={max}
        required={required}
        data-end
        aria-describedby={endDescribedBy}
        class="[[data-haze-date-range-picker][data-enhanced]_&]:[&::-webkit-calendar-picker-indicator]:hidden"
      />
    </div>
    <Button
      variant="outline"
      size="icon"
      disabled={disabled}
      popovertarget={panelId}
      aria-label={`Open calendar for ${label}`}
      aria-haspopup="dialog"
      data-range-trigger
      class="hidden shrink-0 [[data-haze-date-range-picker][data-enhanced]_&]:inline-flex"
    >
      <CalendarRange class="size-4" aria-hidden="true" />
    </Button>
  </div>

  <!-- Stylized Range Calendar Popover -->
  <div
    id={panelId}
    popover="auto"
    role="dialog"
    aria-label={`${label} calendar`}
    data-range-popover
    style={`position-anchor: --${panelId}`}
    class="m-auto max-h-[calc(100dvh-1rem)] w-72 max-w-[calc(100vw-1rem)] -translate-y-1 scale-[0.97] overflow-y-auto rounded-xl border border-border bg-popover p-3.5 text-popover-foreground opacity-0 shadow-float transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 backdrop:bg-background/60 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:m-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline]"
  >
    <p data-range-hint class="mb-2.5 rounded-md bg-muted px-2.5 py-1.5 text-xs font-medium text-foreground">
      Click a start and end date
    </p>
    <div class="mb-2.5 grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1">
      <Button variant="ghost" size="icon" class="size-8" aria-label="Previous month" data-range-prev>
        <ChevronLeft aria-hidden="true" class="rtl:rotate-180" />
      </Button>
      <p id={`${id}-range-month`} data-range-month aria-live="polite" class="text-center text-sm/5 font-medium tracking-[-0.01em]"></p>
      <Button variant="ghost" size="icon" class="size-8" aria-label="Next month" data-range-next>
        <ChevronRight aria-hidden="true" class="rtl:rotate-180" />
      </Button>
    </div>
    <table role="grid" aria-labelledby={`${id}-range-month`} class="w-full table-fixed border-separate border-spacing-y-0.5 text-center text-xs">
      <thead><tr data-range-weekdays></tr></thead>
      <tbody data-range-days></tbody>
    </table>
  </div>

  <p id={`${id}-order`} data-order-status aria-live="polite" class="pt-2 text-xs text-destructive empty:sr-only"></p>
</fieldset>

<script>
  const RANGE_DAY_MS = 86_400_000;
  const parseUtc = (v: string) => (v ? Date.parse(`${v}T00:00:00Z`) : NaN);
  const utcMonthStart = (s: number) => {
    const d = new Date(s);
    d.setUTCDate(1);
    return d.getTime();
  };
  const shiftUtcMonth = (s: number, delta: number) => {
    const d = new Date(utcMonthStart(s));
    d.setUTCMonth(d.getUTCMonth() + delta);
    return d.getTime();
  };

  function enhanceDateRangePickers() {
    document.querySelectorAll<HTMLElement>("[data-haze-date-range-picker]:not([data-enhanced])").forEach((root) => {
      const startIn = root.querySelector<HTMLInputElement>("[data-start]");
      const endIn = root.querySelector<HTMLInputElement>("[data-end]");
      const status = root.querySelector<HTMLElement>("[data-order-status]");
      const trigger = root.querySelector<HTMLButtonElement>("[data-range-trigger]");
      const popup = root.querySelector<HTMLElement>("[data-range-popover]");
      const monthEl = root.querySelector<HTMLElement>("[data-range-month]");
      const wdEl = root.querySelector<HTMLTableRowElement>("[data-range-weekdays]");
      const daysEl = root.querySelector<HTMLTableSectionElement>("[data-range-days]");
      const hintEl = root.querySelector<HTMLElement>("[data-range-hint]");
      const prevBtn = root.querySelector<HTMLButtonElement>("[data-range-prev]");
      const nextBtn = root.querySelector<HTMLButtonElement>("[data-range-next]");
      if (!startIn || !endIn || !status || !popup || !monthEl || !wdEl || !daysEl || !prevBtn || !nextBtn) return;

      const syncValidation = () => {
        const reversed = endIn.valueAsNumber < startIn.valueAsNumber;
        const message = reversed ? (root.dataset.orderError || "The dates are out of order.") : "";
        endIn.setCustomValidity(message);
        if (reversed) endIn.setAttribute("aria-invalid", "true");
        else endIn.removeAttribute("aria-invalid");
        if (status.textContent !== message) status.textContent = message;
      };

      const locale = root.dataset.locale || "en";
      const weekStart = Number(root.dataset.weekStart ?? 1);
      const fmt = (opt: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, { ...opt, calendar: "gregory", timeZone: "UTC" });
      const headingFmt = fmt({ month: "long", year: "numeric" });
      const shortFmt = fmt({ month: "short", day: "numeric" });
      const wdFmt = fmt({ weekday: "narrow" });
      const dayFmt = fmt({ dateStyle: "full" });
      const now = new Date();
      const todayStamp = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
      const minStamp = parseUtc(startIn.min || endIn.min) || parseUtc("0001-01-01");
      const maxStamp = parseUtc(endIn.max || startIn.max) || parseUtc("9999-12-31");
      const colOf = (s: number) => (new Date(s).getUTCDay() + 7 - weekStart) % 7;

      let sStamp = parseUtc(startIn.value);
      let eStamp = parseUtc(endIn.value);
      let viewMonth = utcMonthStart(Number.isFinite(sStamp) ? sStamp : todayStamp);
      let pickingPhase: "start" | "end" = "start";

      for (let i = 0; i < 7; i++) {
        const th = document.createElement("th");
        th.scope = "col";
        th.className = "h-6 text-xs font-medium text-muted-foreground";
        th.textContent = wdFmt.format(Date.UTC(2026, 0, 4 + weekStart + i));
        wdEl.append(th);
      }

      const renderCalendar = () => {
        const nextM = shiftUtcMonth(viewMonth, 1);
        monthEl.textContent = headingFmt.format(viewMonth);
        if (hintEl) {
          if (pickingPhase === "end" && Number.isFinite(sStamp)) {
            hintEl.textContent = `Start: ${shortFmt.format(sStamp)} · Pick end date`;
          } else if (Number.isFinite(sStamp) && Number.isFinite(eStamp)) {
            const count = Math.round((eStamp - sStamp) / RANGE_DAY_MS) + 1;
            hintEl.textContent = `${shortFmt.format(sStamp)} – ${shortFmt.format(eStamp)} (${count}d)`;
          } else {
            hintEl.textContent = "Click a start and end date";
          }
        }

        daysEl.replaceChildren();
        for (let r = viewMonth - colOf(viewMonth) * RANGE_DAY_MS; r < nextM; r += RANGE_DAY_MS * 7) {
          const tr = daysEl.insertRow();
          for (let i = 0; i < 7; i++) {
            const td = tr.insertCell();
            const stamp = r + i * RANGE_DAY_MS;
            if (stamp < viewMonth || stamp >= nextM) continue;
            const isStart = stamp === sStamp;
            const isEnd = stamp === eStamp;
            const inRange = Number.isFinite(sStamp) && Number.isFinite(eStamp) && stamp > sStamp && stamp < eStamp;

            const btn = document.createElement("button");
            btn.type = "button";
            btn.disabled = stamp < minStamp || stamp > maxStamp;
            btn.textContent = String(new Date(stamp).getUTCDate());
            btn.setAttribute("aria-label", dayFmt.format(stamp));
            btn.className =
              "mx-auto grid size-8 w-full cursor-pointer place-items-center text-xs tabular-nums transition-colors duration-100 focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-40 " +
              (isStart || isEnd
                ? "rounded-full bg-primary font-medium text-primary-foreground"
                : inRange
                  ? "bg-accent text-foreground"
                  : "rounded-full text-foreground hover:bg-accent");

            btn.addEventListener("click", () => {
              if (pickingPhase === "start") {
                sStamp = stamp;
                eStamp = NaN;
                pickingPhase = "end";
                startIn.value = new Date(sStamp).toISOString().slice(0, 10);
                startIn.dispatchEvent(new Event("input", { bubbles: true }));
                startIn.dispatchEvent(new Event("change", { bubbles: true }));
                renderCalendar();
              } else {
                if (stamp < sStamp) {
                  eStamp = sStamp;
                  sStamp = stamp;
                } else {
                  eStamp = stamp;
                }
                pickingPhase = "start";
                startIn.value = new Date(sStamp).toISOString().slice(0, 10);
                endIn.value = new Date(eStamp).toISOString().slice(0, 10);
                startIn.dispatchEvent(new Event("input", { bubbles: true }));
                endIn.dispatchEvent(new Event("change", { bubbles: true }));
                syncValidation();
                renderCalendar();
                if (typeof popup.hidePopover === "function") popup.hidePopover();
                trigger?.focus();
              }
            });
            td.append(btn);
          }
        }
      };

      const openCustom = (phase: "start" | "end" = "start") => {
        if (typeof popup.showPopover !== "function") return;
        sStamp = parseUtc(startIn.value);
        eStamp = parseUtc(endIn.value);
        pickingPhase = phase === "end" && Number.isFinite(sStamp) ? "end" : "start";
        renderCalendar();
        if (!popup.matches(":popover-open")) popup.showPopover();
      };

      let closedAt = -Infinity;
      popup.addEventListener("toggle", (ev) => {
        if ((ev as ToggleEvent).newState === "closed") closedAt = performance.now();
        else renderCalendar();
      });

      [
        [startIn, "start"],
        [endIn, "end"],
      ].forEach(([inp, phase]) => {
        const field = inp as HTMLInputElement;
        field.addEventListener("click", (ev) => {
          ev.preventDefault();
          if (performance.now() - closedAt > 250) openCustom(phase as "start" | "end");
        });
        field.addEventListener("keydown", (ev) => {
          if (ev.key === " " || ev.key === "F4" || (ev.altKey && ev.key === "ArrowDown")) {
            ev.preventDefault();
            openCustom(phase as "start" | "end");
          }
        });
        if (typeof field.showPicker === "function") field.showPicker = () => openCustom(phase as "start" | "end");
      });

      prevBtn.addEventListener("click", () => {
        viewMonth = shiftUtcMonth(viewMonth, -1);
        renderCalendar();
      });
      nextBtn.addEventListener("click", () => {
        viewMonth = shiftUtcMonth(viewMonth, 1);
        renderCalendar();
      });

      root.addEventListener("input", () => {
        sStamp = parseUtc(startIn.value);
        eStamp = parseUtc(endIn.value);
        syncValidation();
      });
      root.addEventListener("change", syncValidation);
      for (const form of new Set([startIn.form, endIn.form])) {
        form?.addEventListener("reset", () => queueMicrotask(syncValidation));
      }
      renderCalendar();
      syncValidation();
      root.setAttribute("data-enhanced", "");
    });
  }

  enhanceDateRangePickers();
  if (!document.documentElement.hasAttribute("data-haze-date-range-picker-listener")) {
    document.documentElement.setAttribute("data-haze-date-range-picker-listener", "");
    document.addEventListener("astro:page-load", enhanceDateRangePickers);
  }
</script>
```
