# Shadcn Time Picker

A time picker in two parts. `TimeInput` is a segmented field you type into or step with the arrow keys. `TimePicker` opens a popover with scrollable hour, minute, second and AM/PM wheels. Both support 12 and 24 hour clocks and seconds, and the picker adds minute steps and min and max limits that disable times out of range. Values are plain strings like `"14:30"`, so they store and compare easily.

`time-picker-demo.tsx`:

```tsx
import { TimePicker, TimePickerContent, TimePickerTrigger } from "@/components/ui/time-picker";

export default function TimePickerDemo() {
  return (
    <TimePicker defaultValue="09:30">
      <TimePickerTrigger className="w-40" />
      <TimePickerContent />
    </TimePicker>
  );
}
```

## Installation

```bash
npx shadcn@latest add @shadcnuikit/time-picker1
```

This adds `components/ui/time-picker.tsx`, the `button`, `field`, `input-group` and `popover` components it depends on, and a demo file. Set up the registry once as described in [Shadcn CLI](https://shadcnuikit.com/docs/shadcn-cli). Time Picker is free and installs without an API key.

### Manual installation

Install the dependencies and the shadcn/ui components:

```bash
npm install @ui-sdk/react@beta @ui-sdk/core@beta lucide-react
npx shadcn@latest add button field input-group popover
```

Copy the source into `components/ui/time-picker.tsx`:

`components/ui/time-picker.tsx`:

```tsx
"use client";

import * as React from "react";
import { bindScrollPicker } from "@ui-sdk/core";
import { Listbox, ListboxItem } from "@ui-sdk/react/listbox";
import {
  TimeInput as TimeInputPrimitive,
  TimeInputSegment as TimeInputSegmentPrimitive,
  createTimeInputController,
} from "@ui-sdk/react/time-input";
import { ClockIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import { InputGroup } from "@/components/ui/input-group";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";

type WithClassName<T> = Omit<T, "className"> & { className?: string };

type TimeParts = { hour: number; minute: number; second: number };
type TimeGranularity = "minute" | "second";
type TimeColumnType = "hour" | "minute" | "second" | "period";
type TimeOption = { value: string; label: string; disabled: boolean };

const pad = (n: number) => String(n).padStart(2, "0");

function parseTime(value: string | null | undefined): TimeParts | null {
  const match = value?.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
  if (!match) return null;
  return { hour: Number(match[1]), minute: Number(match[2]), second: Number(match[3] ?? 0) };
}

const toSeconds = (t: TimeParts) => t.hour * 3600 + t.minute * 60 + t.second;

function toTimeString(t: TimeParts, granularity: TimeGranularity = "minute") {
  const base = `${pad(t.hour)}:${pad(t.minute)}`;
  return granularity === "second" ? `${base}:${pad(t.second)}` : base;
}

function formatTime(
  value: string | null | undefined,
  { hourCycle = 12, granularity = "minute" }: { hourCycle?: 12 | 24; granularity?: TimeGranularity } = {},
) {
  const t = parseTime(value);
  if (!t) return "";
  const seconds = granularity === "second" ? `:${pad(t.second)}` : "";
  if (hourCycle === 24) return `${pad(t.hour)}:${pad(t.minute)}${seconds}`;
  const hour = t.hour % 12 || 12;
  return `${hour}:${pad(t.minute)}${seconds} ${t.hour < 12 ? "AM" : "PM"}`;
}

function formatDuration(start: string | null | undefined, end: string | null | undefined) {
  const a = parseTime(start);
  const b = parseTime(end);
  if (!a || !b) return "";
  const minutes = Math.round((toSeconds(b) - toSeconds(a)) / 60);
  if (minutes <= 0) return "";
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  return [h ? `${h} h` : "", m ? `${m} min` : ""].filter(Boolean).join(" ");
}

function range(step: number) {
  return Array.from({ length: Math.ceil(60 / step) }, (_, i) => i * step);
}

type TimePickerContextValue = {
  value: string | null;
  setValue: (value: string | null) => void;
  setPart: (type: TimeColumnType, value: string) => void;
  setNow: () => void;
  clear: () => void;
  options: (type: TimeColumnType) => TimeOption[];
  selected: (type: TimeColumnType) => string | null;
  hourCycle: 12 | 24;
  granularity: TimeGranularity;
  disabled: boolean;
  open: boolean;
  setOpen: (open: boolean) => void;
};

const TimePickerContext = React.createContext<TimePickerContextValue | null>(null);

function useTimePicker() {
  const context = React.useContext(TimePickerContext);
  if (!context) throw new Error("useTimePicker must be used within <TimePicker>");
  return context;
}

type TimePickerProps = {
  value?: string | null;
  defaultValue?: string | null;
  onValueChange?: (value: string | null) => void;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  hourCycle?: 12 | 24;
  granularity?: TimeGranularity;
  minuteStep?: number;
  secondStep?: number;
  min?: string;
  max?: string;
  disabled?: boolean;
  children?: React.ReactNode;
};

function TimePicker({
  value: valueProp,
  defaultValue = null,
  onValueChange,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  hourCycle = 12,
  granularity = "minute",
  minuteStep = 1,
  secondStep = 1,
  min,
  max,
  disabled = false,
  children,
}: TimePickerProps) {
  const [innerValue, setInnerValue] = React.useState(defaultValue);
  const [innerOpen, setInnerOpen] = React.useState(defaultOpen);
  const value = valueProp !== undefined ? valueProp : innerValue;
  const open = openProp ?? innerOpen;

  const setValue = React.useCallback(
    (next: string | null) => {
      if (valueProp === undefined) setInnerValue(next);
      onValueChange?.(next);
    },
    [valueProp, onValueChange],
  );

  const setOpen = React.useCallback(
    (next: boolean) => {
      if (openProp === undefined) setInnerOpen(next);
      onOpenChange?.(next);
    },
    [openProp, onOpenChange],
  );

  const context = React.useMemo<TimePickerContextValue>(() => {
    const minSec = min ? toSeconds(parseTime(min)!) : 0;
    const maxSec = max ? toSeconds(parseTime(max)!) : 86399;
    const minutes = range(minuteStep);
    const seconds = granularity === "second" ? range(secondStep) : [0];
    const inRange = (sec: number) => sec >= minSec && sec <= maxSec;
    const hourEnabled = (h: number) =>
      minutes.some((m) => seconds.some((s) => inRange(h * 3600 + m * 60 + s)));
    const minuteEnabled = (h: number, m: number) =>
      seconds.some((s) => inRange(h * 3600 + m * 60 + s));

    const current = parseTime(value);
    const base = current ?? parseTime(min) ?? { hour: 0, minute: 0, second: 0 };
    const pm = base.hour >= 12;

    const snap = (t: TimeParts): TimeParts => {
      const target = toSeconds(t);
      let best: TimeParts | null = null;
      let bestDiff = Infinity;
      for (let h = 0; h < 24; h++) {
        for (const m of minutes) {
          for (const s of seconds) {
            const sec = h * 3600 + m * 60 + s;
            if (!inRange(sec)) continue;
            const diff = Math.abs(sec - target);
            if (diff < bestDiff) {
              bestDiff = diff;
              best = { hour: h, minute: m, second: s };
            }
          }
        }
      }
      return best ?? t;
    };

    const commit = (t: TimeParts) => setValue(toTimeString(snap(t), granularity));

    return {
      value,
      setValue,
      hourCycle,
      granularity,
      disabled,
      open,
      setOpen,
      clear: () => setValue(null),
      setNow: () => {
        const now = new Date();
        const minute = Math.round(now.getMinutes() / minuteStep) * minuteStep;
        const total = now.getHours() * 60 + minute;
        commit({
          hour: Math.floor(total / 60) % 24,
          minute: total % 60,
          second: granularity === "second" ? Math.floor(now.getSeconds() / secondStep) * secondStep : 0,
        });
      },
      setPart: (type, next) => {
        const t = { ...base };
        const n = Number(next);
        if (type === "hour") t.hour = hourCycle === 12 ? (n % 12) + (pm ? 12 : 0) : n;
        if (type === "minute") t.minute = n;
        if (type === "second") t.second = n;
        if (type === "period") t.hour = (t.hour % 12) + (next === "PM" ? 12 : 0);
        commit(t);
      },
      selected: (type) => {
        if (!current) return null;
        if (type === "hour") return String(hourCycle === 12 ? current.hour % 12 || 12 : current.hour);
        if (type === "minute") return pad(current.minute);
        if (type === "second") return pad(current.second);
        return current.hour < 12 ? "AM" : "PM";
      },
      options: (type) => {
        if (type === "hour") {
          if (hourCycle === 24) {
            return Array.from({ length: 24 }, (_, h) => ({
              value: String(h),
              label: pad(h),
              disabled: !hourEnabled(h),
            }));
          }
          return [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((h) => ({
            value: String(h),
            label: pad(h),
            disabled: !hourEnabled((h % 12) + (pm ? 12 : 0)),
          }));
        }
        if (type === "minute") {
          return minutes.map((m) => ({
            value: pad(m),
            label: pad(m),
            disabled: !minuteEnabled(base.hour, m),
          }));
        }
        if (type === "second") {
          return seconds.map((s) => ({
            value: pad(s),
            label: pad(s),
            disabled: !inRange(base.hour * 3600 + base.minute * 60 + s),
          }));
        }
        return ["AM", "PM"].map((p) => ({
          value: p,
          label: p,
          disabled: !Array.from({ length: 12 }, (_, i) => i + (p === "PM" ? 12 : 0)).some(hourEnabled),
        }));
      },
    };
  }, [value, setValue, open, setOpen, hourCycle, granularity, minuteStep, secondStep, min, max, disabled]);

  return (
    <TimePickerContext.Provider value={context}>
      <Popover open={open} onOpenChange={setOpen}>
        {children}
      </Popover>
    </TimePickerContext.Provider>
  );
}

type TimePickerTriggerProps = React.ComponentProps<typeof Button> & {
  placeholder?: string;
  format?: (value: string) => React.ReactNode;
};

function TimePickerTrigger({
  className,
  children,
  placeholder = "Pick a time",
  format,
  variant = "outline",
  ...props
}: TimePickerTriggerProps) {
  const { value, hourCycle, granularity, disabled } = useTimePicker();
  const label = value ? (format ? format(value) : formatTime(value, { hourCycle, granularity })) : null;

  return (
    <PopoverTrigger asChild>
      <Button
        data-slot="time-picker-trigger"
        data-empty={value ? undefined : ""}
        variant={variant}
        disabled={disabled}
        className={cn(
          "justify-start font-normal tabular-nums data-empty:text-muted-foreground",
          className,
        )}
        {...props}
      >
        {children ?? (
          <>
            <ClockIcon aria-hidden="true" className="text-muted-foreground" />
            {label ?? placeholder}
          </>
        )}
      </Button>
    </PopoverTrigger>
  );
}

function TimePickerContent({
  className,
  children,
  align = "start",
  ...props
}: React.ComponentProps<typeof PopoverContent>) {
  return (
    <PopoverContent
      data-slot="time-picker-content"
      align={align}
      className={cn("w-auto gap-0 p-0", className)}
      {...props}
    >
      {children ?? <TimePickerColumns />}
    </PopoverContent>
  );
}

function TimePickerColumns({ className, children, ...props }: React.ComponentProps<"div">) {
  const { hourCycle, granularity } = useTimePicker();

  return (
    <div
      data-slot="time-picker-columns"
      className={cn(
        "relative isolate flex justify-center gap-1 p-2 [--time-picker-height:--spacing(48)] [--time-picker-row:--spacing(8)]",
        className,
      )}
      {...props}
    >
      <span
        aria-hidden="true"
        className="bg-muted pointer-events-none absolute inset-x-2 top-1/2 -z-10 h-(--time-picker-row) -translate-y-1/2 rounded-md"
      />
      {children ?? (
        <>
          <TimePickerColumn type="hour" />
          <TimePickerColumn type="minute" />
          {granularity === "second" && <TimePickerColumn type="second" />}
          {hourCycle === 12 && <TimePickerColumn type="period" />}
        </>
      )}
    </div>
  );
}

const columnLabels: Record<TimeColumnType, string> = {
  hour: "Hours",
  minute: "Minutes",
  second: "Seconds",
  period: "AM/PM",
};

type TimePickerColumnProps = WithClassName<
  Omit<React.ComponentProps<typeof Listbox>, "value" | "defaultValue" | "onValueChange" | "children">
> & {
  type: TimeColumnType;
  itemClassName?: string;
};

function TimePickerColumn({ type, className, itemClassName, ...props }: TimePickerColumnProps) {
  const { options, selected, setPart, disabled } = useTimePicker();
  const list = React.useRef<HTMLDivElement>(null);
  const items = options(type);
  const value = selected(type);

  const select = React.useEffectEvent((index: number) => {
    const option = items[index];
    if (option && !option.disabled && option.value !== value) setPart(type, option.value);
  });

  React.useLayoutEffect(() => {
    const el = list.current;
    if (!el) return;
    // bindScrollPicker only follows later selections, so start with the selected option centered,
    // waiting for styles when the list can't scroll yet (first paint in dev, closed popovers).
    const index = items.findIndex((option) => option.value === value);
    const center = () => {
      const option = el.querySelectorAll<HTMLElement>('[role="option"]')[index];
      if (!option) return true;
      if (el.scrollHeight <= el.clientHeight) return false;
      el.scrollTop = option.offsetTop - (el.clientHeight - option.offsetHeight) / 2;
      return true;
    };
    const observer = new ResizeObserver(() => center() && observer.disconnect());
    if (!center()) observer.observe(el);
    const unbind = bindScrollPicker(el, { onSelect: (index) => select(index) });
    return () => {
      observer.disconnect();
      unbind();
    };
  }, []);

  return (
    <Listbox
      ref={list}
      aria-label={columnLabels[type]}
      keepInView={false}
      disabled={disabled}
      value={value}
      onValueChange={(next) => {
        if (typeof next === "string") setPart(type, next);
      }}
      className={cn(
        "relative h-(--time-picker-height) w-12 snap-y snap-mandatory overflow-y-auto overscroll-contain py-[calc((var(--time-picker-height)-var(--time-picker-row))/2)] outline-none [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        "mask-[linear-gradient(to_bottom,transparent,black_35%,black_65%,transparent)]",
        className,
      )}
      {...props}
    >
      {items.map((option) => (
        <ListboxItem
          key={option.value}
          value={option.value}
          disabled={option.disabled}
          className={cn(
            "text-muted-foreground flex h-(--time-picker-row) cursor-default snap-center items-center justify-center rounded-md text-sm tabular-nums outline-none select-none",
            "opacity-[calc(1-max(var(--picker-offset,0),calc(var(--picker-offset,0)*-1))*0.18)]",
            "hover:text-foreground aria-selected:text-foreground aria-selected:font-medium focus-visible:ring-ring/50 focus-visible:ring-2",
            "data-disabled:text-muted-foreground/40 data-disabled:line-through data-disabled:hover:text-muted-foreground/40",
            itemClassName,
          )}
        >
          {option.label}
        </ListboxItem>
      ))}
    </Listbox>
  );
}

function TimePickerFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="time-picker-footer"
      className={cn("flex items-center gap-2 border-t p-2", className)}
      {...props}
    />
  );
}

type TimeInputProps = WithClassName<React.ComponentProps<typeof TimeInputPrimitive>> & {
  segmentClassName?: string;
};

function TimeInput({ className, segmentClassName, children, ...props }: TimeInputProps) {
  return (
    <TimeInputPrimitive
      className={cn(
        "border-input dark:bg-input/30 flex h-8 w-full min-w-0 cursor-text items-center rounded-lg border bg-transparent px-2.5 text-base tabular-nums transition-colors md:text-sm",
        "focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-3",
        "data-invalid:border-destructive data-invalid:ring-destructive/20 dark:data-invalid:ring-destructive/40 data-invalid:ring-3",
        "data-disabled:bg-input/50 dark:data-disabled:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
        "in-data-[slot=input-group]:h-full in-data-[slot=input-group]:flex-1 in-data-[slot=input-group]:border-0 in-data-[slot=input-group]:bg-transparent in-data-[slot=input-group]:ps-1.5 in-data-[slot=input-group]:ring-0 in-data-[slot=input-group]:focus-within:ring-0 in-data-[slot=input-group]:data-invalid:ring-0 dark:in-data-[slot=input-group]:bg-transparent",
        className,
      )}
      {...props}
    >
      {children ??
        ((state) =>
          state.segments.map((segment) => (
            <TimeInputSegment key={segment.key} segment={segment} className={segmentClassName} />
          )))}
    </TimeInputPrimitive>
  );
}

function TimeInputSegment({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof TimeInputSegmentPrimitive>>) {
  return (
    <TimeInputSegmentPrimitive
      className={cn(
        "data-[type=literal]:text-muted-foreground data-[type=literal]:px-px data-[type=literal]:whitespace-pre",
        "not-data-[type=literal]:h-5.5 not-data-[type=literal]:w-[calc(2ch+4px)] not-data-[type=literal]:rounded-sm not-data-[type=literal]:bg-transparent not-data-[type=literal]:px-0.5 not-data-[type=literal]:text-center not-data-[type=literal]:caret-transparent not-data-[type=literal]:outline-none",
        "data-[type=dayPeriod]:ms-1 data-[type=dayPeriod]:w-[calc(2.6ch+4px)]",
        "placeholder:text-muted-foreground selection:bg-transparent",
        "focus:bg-primary focus:text-primary-foreground focus:placeholder:text-primary-foreground",
        "data-disabled:cursor-not-allowed",
        className,
      )}
      {...props}
    />
  );
}

function TimeInputGroup({ className, ...props }: React.ComponentProps<typeof InputGroup>) {
  return (
    <InputGroup
      className={cn(
        "has-[[data-slot=time-input]:focus-within]:border-ring has-[[data-slot=time-input]:focus-within]:ring-ring/50 has-[[data-slot=time-input]:focus-within]:ring-3",
        "has-[[data-slot=time-input][data-invalid]]:border-destructive has-[[data-slot=time-input][data-invalid]]:ring-destructive/20 has-[[data-slot=time-input][data-invalid]]:ring-3",
        "has-[[data-slot=time-input][data-disabled]]:opacity-50",
        className,
      )}
      {...props}
    />
  );
}

export {
  TimeInput,
  TimeInputGroup,
  TimeInputSegment,
  TimePicker,
  TimePickerColumn,
  TimePickerColumns,
  TimePickerContent,
  TimePickerFooter,
  TimePickerTrigger,
  createTimeInputController,
  formatDuration,
  formatTime,
  parseTime,
  useTimePicker,
};
export type { TimeColumnType, TimeGranularity, TimeInputProps, TimePickerProps };
```

## Usage

```tsx
import {
  TimeInput,
  TimePicker,
  TimePickerContent,
  TimePickerTrigger,
} from "@/components/ui/time-picker";
```

A typed input:

```tsx
<TimeInput aria-label="Start time" hourCycle={12} defaultValue="09:30" />
```

A button that opens hour and minute wheels:

```tsx
<TimePicker defaultValue="09:30">
  <TimePickerTrigger />
  <TimePickerContent />
</TimePicker>
```

Both take and return 24 hour strings: `"HH:mm"`, or `"HH:mm:ss"` with `granularity="second"`. `null` means no time. The clock you show only changes how the value is displayed.

### Controlled

```tsx
const [value, setValue] = React.useState<string | null>("14:30");

<TimePicker value={value} onValueChange={setValue}>
  <TimePickerTrigger />
  <TimePickerContent />
</TimePicker>;
```

`TimeInput` is controlled the same way. Its `onValueChange` sends `null` while a segment is empty.

### With a label

```tsx
import { Field as FieldPrimitive, FieldLabel as FieldLabelPrimitive } from "@ui-sdk/react/field";
import { Field, FieldLabel } from "@/components/ui/field";

<FieldPrimitive render={<Field />}>
  <FieldLabelPrimitive render={<FieldLabel />}>Meeting time</FieldLabelPrimitive>
  <TimeInput hourCycle={12} defaultValue="09:30" />
</FieldPrimitive>;
```

The ui-sdk `Field` wires the label to the segments. For `TimePickerTrigger`, give it an `id` and use `<FieldLabel htmlFor="...">`.

## Examples

### Time Input

`TimeInput` is a segmented field. Type digits, type `A` or `P` for the period, or step a segment with the arrow keys.

`time-picker-time-input.tsx`:

```tsx
import { TimeInput } from "@/components/ui/time-picker";

export default function TimePickerTimeInput() {
  return <TimeInput aria-label="Time" hourCycle={12} defaultValue="14:30" className="w-40" />;
}
```

### Inline

Render `TimePickerColumns` inside `TimePicker` without a trigger or content to show the wheels on the page.

`time-picker-inline.tsx`:

```tsx
import { TimePicker, TimePickerColumns } from "@/components/ui/time-picker";

export default function TimePickerInline() {
  return (
    <div className="rounded-lg border">
      <TimePicker defaultValue="18:45">
        <TimePickerColumns />
      </TimePicker>
    </div>
  );
}
```

### Hour Cycle

`hourCycle` accepts `12` or `24`. The value stays a 24 hour string either way.

`time-picker-hour-cycle.tsx`:

```tsx
import { TimeInput } from "@/components/ui/time-picker";

export default function TimePickerHourCycle() {
  return (
    <div className="flex w-40 flex-col gap-4">
      <TimeInput aria-label="12-hour time" hourCycle={12} defaultValue="18:45" />
      <TimeInput aria-label="24-hour time" hourCycle={24} defaultValue="18:45" />
    </div>
  );
}
```

### Seconds

`granularity="second"` adds a seconds segment and a seconds wheel. The value becomes `"HH:mm:ss"`.

`time-picker-seconds.tsx`:

```tsx
import { TimeInput, TimePicker, TimePickerColumns } from "@/components/ui/time-picker";

export default function TimePickerSeconds() {
  return (
    <div className="flex flex-col items-center gap-4">
      <TimeInput aria-label="Time with seconds" hourCycle={24} granularity="second" defaultValue="08:15:30" className="w-40" />
      <div className="rounded-lg border">
        <TimePicker hourCycle={24} granularity="second" defaultValue="08:15:30">
          <TimePickerColumns />
        </TimePicker>
      </div>
    </div>
  );
}
```

### Minute Step

`minuteStep` sets the gap between minutes in the wheel. `secondStep` does the same for seconds.

`time-picker-minute-step.tsx`:

```tsx
import { TimePicker, TimePickerColumns } from "@/components/ui/time-picker";

export default function TimePickerMinuteStep() {
  return (
    <div className="rounded-lg border">
      <TimePicker hourCycle={24} minuteStep={15} defaultValue="10:45">
        <TimePickerColumns />
      </TimePicker>
    </div>
  );
}
```

### Min and Max

`min` and `max` disable every hour and minute outside the range. Picked times snap to the closest allowed time.

`time-picker-min-max.tsx`:

```tsx
import { TimePicker, TimePickerColumns } from "@/components/ui/time-picker";

export default function TimePickerMinMax() {
  return (
    <div className="rounded-lg border">
      <TimePicker hourCycle={24} minuteStep={30} min="09:00" max="17:00" defaultValue="12:00">
        <TimePickerColumns />
      </TimePicker>
    </div>
  );
}
```

### With Icon

Wrap `TimeInput` in `TimeInputGroup` to add an `InputGroupAddon`.

`time-picker-with-icon.tsx`:

```tsx
import { ClockIcon } from "lucide-react";

import { InputGroupAddon } from "@/components/ui/input-group";
import { TimeInput, TimeInputGroup } from "@/components/ui/time-picker";

export default function TimePickerWithIcon() {
  return (
    <TimeInputGroup className="w-40">
      <InputGroupAddon>
        <ClockIcon aria-hidden="true" />
      </InputGroupAddon>
      <TimeInput aria-label="Time" hourCycle={12} defaultValue="07:00" />
    </TimeInputGroup>
  );
}
```

### Footer

Add `TimePickerFooter` inside the content and call `setNow`, `clear` and `setOpen` from `useTimePicker`.

`time-picker-footer.tsx`:

```tsx
"use client";

import { Button } from "@/components/ui/button";
import {
  TimePicker,
  TimePickerColumns,
  TimePickerContent,
  TimePickerFooter,
  TimePickerTrigger,
  useTimePicker,
} from "@/components/ui/time-picker";

function Actions() {
  const { setNow, clear, setOpen } = useTimePicker();

  return (
    <TimePickerFooter>
      <Button variant="ghost" size="sm" onClick={setNow}>
        Now
      </Button>
      <Button variant="ghost" size="sm" onClick={clear}>
        Clear
      </Button>
      <Button size="sm" className="ms-auto" onClick={() => setOpen(false)}>
        Done
      </Button>
    </TimePickerFooter>
  );
}

export default function TimePickerFooterDemo() {
  return (
    <TimePicker defaultValue="10:15">
      <TimePickerTrigger className="w-40" />
      <TimePickerContent>
        <TimePickerColumns />
        <Actions />
      </TimePickerContent>
    </TimePicker>
  );
}
```

### Disabled and Read Only

`readOnly` keeps the input focusable but stops changes. `disabled` turns off the input or the picker trigger.

`time-picker-disabled.tsx`:

```tsx
import { TimeInput, TimePicker, TimePickerContent, TimePickerTrigger } from "@/components/ui/time-picker";

export default function TimePickerDisabled() {
  return (
    <div className="flex w-40 flex-col gap-4">
      <TimeInput aria-label="Read-only time" hourCycle={12} defaultValue="15:00" readOnly />
      <TimeInput aria-label="Disabled time" hourCycle={12} defaultValue="11:00" disabled />
      <TimePicker defaultValue="13:00" disabled>
        <TimePickerTrigger />
        <TimePickerContent />
      </TimePicker>
    </div>
  );
}
```

More layouts built with Time Picker, such as time ranges, quick picks and date and time together, are on the [Time Picker components](https://shadcnuikit.com/components/time-picker) page.

## API Reference

### TimePicker

The root of the popover picker. It holds the value and the open state and renders no element of its own.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string \| null` | | The time, like `"14:30"`. Pass it to control the picker. |
| `defaultValue` | `string \| null` | `null` | The time at first, when uncontrolled. |
| `onValueChange` | `(value: string \| null) => void` | | Runs when a wheel, `setNow` or `clear` changes the time. |
| `open` | `boolean` | | Whether the popover is open. Pass it to control it. |
| `defaultOpen` | `boolean` | `false` | Whether the popover starts open. |
| `onOpenChange` | `(open: boolean) => void` | | Runs when the popover opens or closes. |
| `hourCycle` | `12`, `24` | `12` | Shows a 12 hour clock with an AM/PM wheel, or a 24 hour clock. |
| `granularity` | `"minute"`, `"second"` | `"minute"` | Adds a seconds wheel with `"second"`. |
| `minuteStep` | `number` | `1` | The gap between minutes in the wheel. |
| `secondStep` | `number` | `1` | The gap between seconds in the wheel. |
| `min` | `string` | | The earliest time, like `"09:00"`. Earlier options are disabled. |
| `max` | `string` | | The latest time, like `"17:30"`. Later options are disabled. |
| `disabled` | `boolean` | `false` | Disables the trigger and every wheel. |

### TimePickerTrigger

The button that opens the popover. It takes every `Button` prop.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `placeholder` | `string` | `"Pick a time"` | The text shown while there is no time. |
| `format` | `(value: string) => ReactNode` | | Formats the time label. Without it, `formatTime` uses the picker's clock. |
| `variant` | `Button` variant | `"outline"` | The button variant. |
| `children` | `ReactNode` | | Replaces the clock icon and the label. |
| `className` | `string` | | Classes for the button. |

The button has `data-empty` while there is no time.

### TimePickerContent

The popover. It takes every `PopoverContent` prop and renders `TimePickerColumns` when it has no children.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `align` | `"start"`, `"center"`, `"end"` | `"start"` | How the popover lines up with the trigger. |
| `children` | `ReactNode` | `<TimePickerColumns />` | The popover content, such as columns and a footer. |
| `className` | `string` | | Classes for the popover. |

### TimePickerColumns

The row of wheels with the highlight band behind the selected row. Without children it renders hour and minute columns, a second column with `granularity="second"`, and a period column with `hourCycle={12}`. It takes every `div` prop.

Set `--time-picker-height` and `--time-picker-row` in `className` to change the wheel height and the row height.

### TimePickerColumn

One wheel. Scrolling snaps to the centered option and selects it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `"hour"`, `"minute"`, `"second"`, `"period"` | | Which part of the time the wheel edits. |
| `itemClassName` | `string` | | Classes for each option. |
| `className` | `string` | | Classes for the wheel. |

### TimePickerFooter

A bordered row for actions under the wheels. It takes every `div` prop.

### TimeInput

The segmented text field. It works without `TimePicker`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string \| null` | | The time, like `"14:30"` or `"14:30:15"`. Pass it to control the input. |
| `defaultValue` | `string \| null` | | The time at first, when uncontrolled. A form reset returns to it. |
| `onValueChange` | `(value, details) => void` | | Runs once every segment holds something, and with `null` when one is emptied. `details.cancel()` keeps the value. |
| `granularity` | `"hour"`, `"minute"`, `"second"` | `"minute"` | The smallest segment shown. |
| `hourCycle` | `12`, `24` | the locale's | A 12 or 24 hour clock. |
| `min` | `string` | | The earliest time. Earlier times mark the input invalid. |
| `max` | `string` | | The latest time. Later times mark the input invalid. |
| `locale` | `string` | the page's | The language for separators and the clock. |
| `disabled` | `boolean` | `false` | Turns the input off. |
| `readOnly` | `boolean` | `false` | Shows the time but stops changes. |
| `required` | `boolean` | `false` | Blocks form submission until a time is entered. |
| `name` | `string` | | The name the time submits under. |
| `form` | `string` | | The id of a form to belong to, when the input is outside it. |
| `controller` | `TimeInputController` | | Drives the input from anywhere. Create one with `createTimeInputController()`. |
| `segmentClassName` | `string` | | Classes for every segment. |
| `children` | `(state) => ReactNode` | | Renders `state.segments` yourself with `TimeInputSegment`. |
| `className` | `string` | | Classes for the root. |

The root has `data-invalid` when the time is out of range, and `data-disabled` when it is disabled.

### TimeInputSegment

One segment, such as the hour. Pass it the `segment` from `state.segments`. Style segments by type with `data-[type=hour]`, `data-[type=dayPeriod]` or `data-[type=literal]`.

### TimeInputGroup

An `InputGroup` that shows the focus and invalid ring of the `TimeInput` inside it. Use it with `InputGroupAddon`.

### useTimePicker

Reads the picker from any child of `TimePicker`.

```tsx
const { value, setValue, setNow, clear, open, setOpen } = useTimePicker();
```

`setNow` picks the current time, rounded to `minuteStep` and kept within `min` and `max`. `clear` sets the value to `null`.

### Helpers

| Export | Description |
| --- | --- |
| `formatTime(value, { hourCycle, granularity })` | Formats `"18:45"` as `"6:45 PM"` or `"18:45"`. Returns `""` for no time. |
| `parseTime(value)` | Returns `{ hour, minute, second }`, or `null` when the string is not a time. |
| `formatDuration(start, end)` | Returns the gap between two times, like `"1 h 30 min"`, or `""` when `end` is not later. |
| `createTimeInputController()` | Returns `getValue`, `setValue`, `clear` and `focus(segment)` for a `TimeInput`. |

## Keyboard

### TimeInput

| Key | Action |
| --- | --- |
| `0` to `9` | Fills the focused segment and moves to the next one when it is full. |
| `A`, `P` | Sets AM or PM on a 12 hour clock. |
| `ArrowUp`, `ArrowDown` | Steps the focused segment up or down by one. |
| `PageUp`, `PageDown` | Steps by 3 hours, or 15 minutes or seconds. |
| `Home`, `End` | Sets the focused segment to its lowest or highest value. |
| `ArrowLeft`, `ArrowRight` | Moves to the previous or next segment. |
| `Backspace`, `Delete` | Clears the focused segment. |

### TimePicker

| Key | Action |
| --- | --- |
| `Enter`, `Space` | Opens the popover from the trigger. |
| `Tab` | Moves between the wheels. |
| `ArrowUp`, `ArrowDown` | Selects the previous or next option in the focused wheel, skipping disabled ones. |
| `Home`, `End` | Selects the first or last option. |
| `Escape` | Closes the popover and returns focus to the trigger. |

## Accessibility

- Each `TimeInput` segment is a `spinbutton` named by its unit in the page language, with its value and range announced. The root is a `group`.
- Each wheel is a `listbox` named "Hours", "Minutes", "Seconds" or "AM/PM", and every time is an `option`. Disabled times have `aria-disabled`.
- Give a `TimeInput` a name with a ui-sdk `FieldLabel` or `aria-label`. The trigger is named by the time it shows, or by a `FieldLabel` with `htmlFor`.
- Out of range times in `TimeInput` set `aria-invalid` on the segments.

## For AI Agents

**When to use**

- Picking a time of day: meeting times, reminders, opening hours, delivery slots, alarms.
- `TimeInput` when users know the time and want to type it. `TimePicker` when they browse slots with a mouse or touch.
- Limited slots, such as every 15 minutes between 09:00 and 17:00, with `minuteStep`, `min` and `max`.

**When not to use**

- Picking a date. Use a [Calendar](https://shadcnuikit.com/components/calendar).
- A duration or a count of minutes. Use a [Number Input](https://shadcnuikit.com/components/number-input).
- A few fixed slots, such as Morning, Afternoon or Evening. Use a [Select](https://shadcnuikit.com/components/select) or a [Radio Group](https://shadcnuikit.com/components/radio-group).

**Agent notes**

- Import from `@/components/ui/time-picker`. The exports are `TimeInput`, `TimeInputGroup`, `TimeInputSegment`, `TimePicker`, `TimePickerTrigger`, `TimePickerContent`, `TimePickerColumns`, `TimePickerColumn`, `TimePickerFooter`, `useTimePicker`, `formatTime`, `parseTime`, `formatDuration` and `createTimeInputController`.
- Values are 24 hour strings, `"HH:mm"` or `"HH:mm:ss"`, never `Date` objects. Type state as `string | null`.
- `TimePicker` defaults to `hourCycle={12}`. `TimeInput` defaults to the locale's clock, so pass `hourCycle` to both when they must match.
- `TimePicker` does not submit with a form. Use `TimeInput` with `name`, or a hidden input fed by `value`.
- `useTimePicker` only works inside `TimePicker`. Put footer buttons in their own component under `TimePickerContent`.

**Resources**

- Markdown: [/docs/components/time-picker.md](https://shadcnuikit.com/docs/components/time-picker.md)
- Variants: [Time Picker components](https://shadcnuikit.com/components/time-picker), 10 free examples
- Install: `npx shadcn@latest add @shadcnuikit/time-picker1`
- MCP: call `get_item_code` with `time-picker1` from the [MCP Server](https://shadcnuikit.com/docs/mcp-server)
- Full index for agents: [llms.txt](https://shadcnuikit.com/llms.txt)

Source: https://shadcnuikit.com/docs/components/time-picker
More from Shadcn UI Kit: [llms.txt](https://shadcnuikit.com/llms.txt)