# Datetime picker

> Combined date and time selector in an anchored popover with preset time slots, timezone label, and native input fallback.

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

## Use when
- Scheduling releases, webhooks, or calendar events to a specific date and time
- Forms needing combined timestamp entry with clear timezone context

## Avoid when
- Only a calendar day is required; use date-picker
- Only a clock time is required; use time-picker

## Alternatives
- [date-picker](https://hazeui.com/ui/date-picker.md)
- [time-picker](https://hazeui.com/ui/time-picker.md)
- [date-range-picker](https://hazeui.com/ui/date-range-picker.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique DOM id backing the underlying datetime-local input. |
| label | `string` | "Publish date and time" | no | Visible field label. |
| value | `string` | "2026-11-21T14:30" | no | ISO local datetime string YYYY-MM-DDTHH:MM. |
| timezone | `string` | "UTC" | no | Short timezone indicator shown next to the label. |

## Accessibility
- Falls back cleanly to native <input type='datetime-local'> when popover APIs are unavailable.
- Trigger button opens the anchored popover and restores focus cleanly when Done is pressed.
- Key Escape: Dismisses the datetime popover and returns focus to the trigger.

## Agent prompts

### Install and use

Install the Haze UI component "Datetime picker" with `npx shadcn@latest add @haze/datetime-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 DatetimePicker from "@/components/haze/ui/datetime-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/datetime-picker.md

### Customize with real content

Adapt the Haze datetime-picker ui for our product. Replace the demo values of these props with our real content: id, label, value, timezone. Keep the layout, the heading level rules and these accessibility details: Falls back cleanly to native <input type='datetime-local'> when popover APIs are unavailable. Trigger button opens the anchored popover and restores focus cleanly when Done is pressed. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using datetime-picker, check it fits: use it when scheduling releases, webhooks, or calendar events to a specific date and time; forms needing combined timestamp entry with clear timezone context. Avoid it when only a calendar day is required; use date-picker; only a clock time is required; use time-picker. Alternatives: @haze/date-picker, @haze/time-picker, @haze/date-range-picker.

## Example requests that should lead here
- Add a datetime picker for scheduling an announcement publish timestamp in UTC

## Source

```astro
---
import { CalendarClock, ChevronLeft, ChevronRight, Clock } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id: string;
  name?: string;
  label?: string;
  value?: string;
  timezone?: string;
  locale?: string;
  weekStart?: 0 | 1;
  required?: boolean;
  disabled?: boolean;
  class?: string;
  [key: string]: unknown;
}

const {
  id,
  name = id,
  label = "Publish date and time",
  value = "2026-11-21T14:30",
  timezone = "UTC",
  locale = "en",
  weekStart = 1,
  required = false,
  disabled = false,
  class: className,
  ...rest
} = Astro.props;

const [initDate = "2026-11-21", initTime = "14:30"] = value.split("T");
const [initHour = "14", initMinute = "30"] = initTime.split(":");
const hours = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, "0"));
const minutes = Array.from({ length: 12 }, (_, i) => String(i * 5).padStart(2, "0"));
---

<div
  id={`${id}-wrap`}
  data-haze-datetime-picker
  data-locale={locale}
  data-week-start={weekStart}
  class={cn("grid min-w-0 gap-2", className)}
>
  <div class="flex items-center justify-between gap-2">
    <label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
    {timezone && <span class="rounded-sm bg-muted px-1.5 py-0.5 font-mono text-[0.6875rem] text-muted-foreground">{timezone}</span>}
  </div>

  <input
    {...rest}
    id={id}
    name={name}
    type="datetime-local"
    value={value}
    required={required}
    disabled={disabled}
    data-dt-native
    class="h-10 w-full min-w-0 rounded-lg border border-frame-input bg-field px-3 font-mono text-sm text-foreground transition-[color,background-color,border-color,box-shadow] duration-150 hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus:outline-hidden [[data-haze-datetime-picker][data-enhanced]_&]:hidden"
  />

  <button
    type="button"
    data-dt-trigger
    hidden
    disabled={disabled}
    popovertarget={`${id}-popover`}
    style={`anchor-name: --${id}-dt`}
    class="hidden h-10 w-full cursor-pointer items-center justify-between gap-2 rounded-lg border border-frame bg-field px-3 text-left text-[0.8125rem]/5 text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden [[data-haze-datetime-picker][data-enhanced]_&]:flex"
  >
    <span data-dt-display class="truncate font-mono text-xs tabular-nums">{initDate} · {initTime}</span>
    <CalendarClock class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
  </button>

  <div
    id={`${id}-popover`}
    data-dt-panel
    popover
    style={`position-anchor: --${id}-dt`}
    class="m-auto max-h-[min(32rem,calc(100dvh-1rem))] w-[min(22rem,calc(100vw-1rem))] overflow-y-auto rounded-xl border border-border bg-popover p-3.5 text-popover-foreground shadow-float backdrop:bg-background/60 scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 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 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]"
  >
    <div class="grid gap-3">
      <!-- Stylized Month Calendar -->
      <div>
        <div class="mb-2.5 grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1">
          <button
            type="button"
            data-dt-prev
            aria-label="Previous month"
            class="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground active:scale-90 focus-visible:outline-2 focus-visible:outline-ring"
          >
            <ChevronLeft class="size-4" aria-hidden="true" />
          </button>
          <p id={`${id}-month`} data-dt-month aria-live="polite" class="text-center text-sm/5 font-medium tracking-[-0.01em] text-foreground"></p>
          <button
            type="button"
            data-dt-next
            aria-label="Next month"
            class="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground active:scale-90 focus-visible:outline-2 focus-visible:outline-ring"
          >
            <ChevronRight class="size-4" aria-hidden="true" />
          </button>
        </div>
        <table role="grid" aria-labelledby={`${id}-month`} class="w-full table-fixed border-separate border-spacing-y-0.5 text-center text-xs">
          <thead><tr data-dt-weekdays></tr></thead>
          <tbody data-dt-days></tbody>
        </table>
      </div>

      <!-- Stylized Two-Column Hour / Minute Selector -->
      <div class="border-t border-border pt-3">
        <div class="mb-2 flex items-center justify-between text-xs">
          <span class="inline-flex items-center gap-1.5 font-medium text-foreground">
            <Clock class="size-3.5 text-muted-foreground" aria-hidden="true" />
            <span>Time ({timezone})</span>
          </span>
          <span data-dt-time-readout class="font-mono text-foreground tabular-nums">{initTime}</span>
        </div>

        <div class="grid grid-cols-2 gap-2">
          <div class="rounded-lg border border-border bg-card p-1">
            <p class="px-1.5 pb-1 text-[0.6875rem] font-medium text-muted-foreground">Hour</p>
            <div role="listbox" aria-label="Hour" data-dt-hours class="grid max-h-28 grid-cols-3 gap-0.5 overflow-y-auto">
              {
                hours.map((h) => (
                  <button
                    type="button"
                    role="option"
                    aria-selected={h === initHour ? "true" : "false"}
                    data-dt-hour={h}
                    class="h-7 cursor-pointer rounded-sm font-mono text-xs tabular-nums text-muted-foreground transition-colors duration-75 hover:bg-accent hover:text-foreground aria-selected:bg-primary aria-selected:font-medium aria-selected:text-primary-foreground focus-visible:outline-2 focus-visible:outline-ring"
                  >
                    {h}
                  </button>
                ))
              }
            </div>
          </div>

          <div class="rounded-lg border border-border bg-card p-1">
            <p class="px-1.5 pb-1 text-[0.6875rem] font-medium text-muted-foreground">Minute</p>
            <div role="listbox" aria-label="Minute" data-dt-minutes class="grid max-h-28 grid-cols-3 gap-0.5 overflow-y-auto">
              {
                minutes.map((m) => (
                  <button
                    type="button"
                    role="option"
                    aria-selected={m === initMinute ? "true" : "false"}
                    data-dt-min={m}
                    class="h-7 cursor-pointer rounded-sm font-mono text-xs tabular-nums text-muted-foreground transition-colors duration-75 hover:bg-accent hover:text-foreground aria-selected:bg-primary aria-selected:font-medium aria-selected:text-primary-foreground focus-visible:outline-2 focus-visible:outline-ring"
                  >
                    {m}
                  </button>
                ))
              }
            </div>
          </div>
        </div>
      </div>

      <div class="flex items-center justify-between border-t border-border pt-2.5">
        <button
          type="button"
          data-dt-now
          class="inline-flex h-7 cursor-pointer items-center rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
        >
          Set to now
        </button>
        <button
          type="button"
          data-dt-done
          class="inline-flex h-7 cursor-pointer items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 hover:opacity-91 active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-ring"
        >
          Done
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  const DAY_MS = 86_400_000;
  const monthStart = (stamp: number) => {
    const d = new Date(stamp);
    d.setUTCDate(1);
    return d.getTime();
  };
  const shiftMonthStamp = (stamp: number, delta: number) => {
    const d = new Date(monthStart(stamp));
    d.setUTCMonth(d.getUTCMonth() + delta);
    return d.getTime();
  };

  function initDatetimePickers() {
    document.querySelectorAll<HTMLElement>("[data-haze-datetime-picker]:not([data-enhanced])").forEach((root) => {
      const native = root.querySelector<HTMLInputElement>("[data-dt-native]");
      const trigger = root.querySelector<HTMLButtonElement>("[data-dt-trigger]");
      const display = root.querySelector<HTMLElement>("[data-dt-display]");
      const timeReadout = root.querySelector<HTMLElement>("[data-dt-time-readout]");
      const panel = root.querySelector<HTMLElement>("[data-dt-panel]");
      const monthEl = root.querySelector<HTMLElement>("[data-dt-month]");
      const weekdaysEl = root.querySelector<HTMLTableRowElement>("[data-dt-weekdays]");
      const daysEl = root.querySelector<HTMLTableSectionElement>("[data-dt-days]");
      const prevBtn = root.querySelector<HTMLButtonElement>("[data-dt-prev]");
      const nextBtn = root.querySelector<HTMLButtonElement>("[data-dt-next]");
      const hourBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-dt-hour]"));
      const minBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-dt-min]"));

      if (!native || !trigger || !panel || !monthEl || !weekdaysEl || !daysEl || !prevBtn || !nextBtn) return;
      if (typeof panel.showPopover !== "function") return;

      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 wdFmt = fmt({ weekday: "narrow" });
      const dayFmt = fmt({ dateStyle: "full" });
      const nowLocal = new Date();
      const todayStamp = Date.UTC(nowLocal.getFullYear(), nowLocal.getMonth(), nowLocal.getDate());
      const colOf = (stamp: number) => (new Date(stamp).getUTCDay() + 7 - weekStart) % 7;

      const [rawD = "2026-11-21", rawT = "14:30"] = (native.value || "2026-11-21T14:30").split("T");
      let selectedStamp = Date.parse(`${rawD}T00:00:00Z`) || todayStamp;
      let viewMonth = monthStart(selectedStamp);
      let [selH = "14", selM = "30"] = rawT.split(":");

      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));
        weekdaysEl.append(th);
      }

      const syncValue = () => {
        const isoDate = new Date(selectedStamp).toISOString().slice(0, 10);
        const hm = `${selH}:${selM}`;
        native.value = `${isoDate}T${hm}`;
        if (display) display.textContent = `${isoDate} · ${hm}`;
        if (timeReadout) timeReadout.textContent = hm;
        hourBtns.forEach((b) => b.setAttribute("aria-selected", String(b.dataset.dtHour === selH)));
        minBtns.forEach((b) => b.setAttribute("aria-selected", String(b.dataset.dtMin === selM)));
        native.dispatchEvent(new Event("change", { bubbles: true }));
      };

      const renderCalendar = () => {
        const nextM = shiftMonthStamp(viewMonth, 1);
        monthEl.textContent = headingFmt.format(viewMonth);
        daysEl.replaceChildren();
        for (let rowStart = viewMonth - colOf(viewMonth) * DAY_MS; rowStart < nextM; rowStart += DAY_MS * 7) {
          const tr = daysEl.insertRow();
          for (let i = 0; i < 7; i++) {
            const td = tr.insertCell();
            const stamp = rowStart + i * DAY_MS;
            if (stamp < viewMonth || stamp >= nextM) continue;
            const btn = document.createElement("button");
            btn.type = "button";
            btn.textContent = String(new Date(stamp).getUTCDate());
            btn.setAttribute("aria-label", dayFmt.format(stamp));
            const isSel = stamp === selectedStamp;
            const isToday = stamp === todayStamp;
            btn.className =
              "mx-auto grid size-8 cursor-pointer place-items-center rounded-full text-xs tabular-nums transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-ring " +
              (isSel
                ? "bg-primary font-medium text-primary-foreground"
                : "text-foreground hover:bg-accent" + (isToday ? " underline underline-offset-4" : ""));
            btn.addEventListener("click", () => {
              selectedStamp = stamp;
              syncValue();
              renderCalendar();
            });
            td.append(btn);
          }
        }
      };

      prevBtn.addEventListener("click", () => {
        viewMonth = shiftMonthStamp(viewMonth, -1);
        renderCalendar();
      });
      nextBtn.addEventListener("click", () => {
        viewMonth = shiftMonthStamp(viewMonth, 1);
        renderCalendar();
      });

      hourBtns.forEach((b) => {
        b.addEventListener("click", () => {
          selH = b.dataset.dtHour ?? "14";
          syncValue();
        });
      });

      minBtns.forEach((b) => {
        b.addEventListener("click", () => {
          selM = b.dataset.dtMin ?? "30";
          syncValue();
        });
      });

      root.querySelector<HTMLButtonElement>("[data-dt-now]")?.addEventListener("click", () => {
        const now = new Date();
        selectedStamp = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
        viewMonth = monthStart(selectedStamp);
        selH = String(now.getHours()).padStart(2, "0");
        selM = String(Math.floor(now.getMinutes() / 5) * 5).padStart(2, "0");
        syncValue();
        renderCalendar();
      });

      root.querySelector<HTMLButtonElement>("[data-dt-done]")?.addEventListener("click", () => {
        syncValue();
        panel.hidePopover();
        trigger.focus();
      });

      renderCalendar();
      syncValue();
      trigger.hidden = false;
      root.setAttribute("data-enhanced", "");
    });
  }

  initDatetimePickers();
  if (!document.documentElement.hasAttribute("data-haze-dt-listener")) {
    document.documentElement.setAttribute("data-haze-dt-listener", "");
    document.addEventListener("astro:page-load", initDatetimePickers);
  }
</script>
```
