# Time Input

A time field typed one part at a time, like a native time input.

Source: [time-input.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/time-input.tsx)

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

export default function TimeInputBasic() {
  return <TimeInput aria-label="Start time" />;
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/time-input
```

## Usage

```tsx
"use client";

import * as React from "react";

import { TimeInput } from "@/components/ui/time-input";

export function StartTimeInput() {
  const [time, setTime] = React.useState<string | null>(null);

  return <TimeInput aria-label="Start time" value={time} onValueChange={setTime} />;
}
```

`TimeInput` splits the time into parts: an hour, a minute and, on a 12-hour clock, AM or PM. Each
part accepts typed digits and moves to the next part once it's filled, so typing `9`, `3`, `0`, `p`
gives 9:30 PM. Typing `a` or `p` in any part sets AM or PM, and a `:`, `.` or space moves to the
next part early. The arrow keys step a part up and down, Page Up and Page Down step the hour by 2
and the minute by 15, and Backspace clears the part. Pasting a time such as `14:30`, `2:30 pm` or
`1430` fills every part, and pasting a number such as `45` fills only the focused part.

The value is a 24-hour `HH:mm` string, such as `"21:30"`, the same format as a native time input.
`onValueChange` receives the value once every part is filled in, and `null` once any part is
cleared. To also offer a list of times to pick from, use a [Time Picker](https://ui.jarv.is/components/time-picker.md),
which is built on Time Input.

## Examples

### With a label

Put the input in a [`Field`](https://ui.jarv.is/components/field.md) with a `FieldLabel`. Screen readers read the
field's `FieldDescription` and `FieldError` with the input, and the input turns invalid or disabled
with the field. Without a visible label, give it an `aria-label`.

```tsx
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { TimeInput } from "@/components/ui/time-input";

export default function TimeInputWithLabel() {
  return (
    <Field className="w-48">
      <FieldLabel>Alarm</FieldLabel>
      <TimeInput defaultValue="06:45" className="w-full" />
      <FieldDescription>Rings every day.</FieldDescription>
    </Field>
  );
}
```

### Hour cycle

The input follows the hour cycle of its `locale`, a BCP 47 tag such as `"de-DE"`. The default,
`"en-US"`, uses a 12-hour clock.
`hourCycle={24}` runs hours from 0 to 23 instead, with no AM or PM. In locales that put AM or PM
first, such as Chinese, the input does too.

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

export default function TimeInputCustomHourCycle() {
  return <TimeInput hourCycle={24} defaultValue="18:45" aria-label="Departure time" />;
}
```

### Earliest and latest times

The input turns invalid outside `min` and `max`. A `min` later than `max` makes a range that runs
past midnight, so `min="20:00" max="02:00"` accepts times from 8:00 PM to 2:00 AM.

```tsx
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { TimeInput } from "@/components/ui/time-input";

export default function TimeInputMinMax() {
  return (
    <Field className="w-48">
      <FieldLabel>Quiet hours start</FieldLabel>
      <TimeInput min="20:00" max="02:00" defaultValue="22:00" className="w-full" />
      <FieldDescription>Between 8:00 PM and 2:00 AM.</FieldDescription>
    </Field>
  );
}
```

### Seconds

`granularity="second"` adds seconds, and the value becomes `HH:mm:ss`.

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { TimeInput } from "@/components/ui/time-input";

export default function TimeInputSeconds() {
  return (
    <Field className="w-48">
      <FieldLabel>Clip starts at</FieldLabel>
      <TimeInput granularity="second" hourCycle={24} defaultValue="00:01:30" />
    </Field>
  );
}
```

### Labels

`labels` replaces the input's built-in text, the parts' accessible names and its validation
messages, so you can translate the input into another language. Pass only the labels you want to
change.

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

export default function TimeInputCustomLabels() {
  return (
    <TimeInput
      locale="de-DE"
      defaultValue="18:45"
      aria-label="Abfahrt"
      labels={{
        hour: "Stunde",
        minute: "Minute",
        empty: "Leer",
        incomplete: "Gib eine vollständige Uhrzeit ein.",
      }}
    />
  );
}
```

### In a form

Give a `Field` or the input a `name`, and the value submits under it as `HH:mm`. Pass `form` with
a form's `id` when the input sits outside the form. With `required`, the form won't submit without
a time, failing validation with `valueMissing`. A time outside `min` and `max`, or a partly typed
one, also blocks submission, failing with `customError`. A `FieldError` that matches `customError`
shows the reason, in the words of `labels`. A form reset restores `defaultValue`.

```tsx
"use client";

import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import { TimeInput } from "@/components/ui/time-input";
import { toast } from "@/components/ui/toast";

export default function TimeInputForm() {
  return (
    <Form
      className="max-w-sm"
      onFormSubmit={(values) =>
        toast.add({ title: "Table booked", description: `We'll see you at ${values.arrival}.` })
      }
    >
      <Field name="arrival">
        <FieldLabel>Arrival</FieldLabel>
        <TimeInput required min="17:00" max="22:30" className="w-full" />
        <FieldDescription>We seat from 5:00 PM to 10:30 PM.</FieldDescription>
        <FieldError match="valueMissing">Enter when you'll arrive.</FieldError>
        <FieldError match="customError" />
      </Field>
      <Button type="submit" variant="primary" className="self-start">
        Book table
      </Button>
    </Form>
  );
}
```

### Sizes

`size` matches the sizes of [Button](https://ui.jarv.is/components/button.md), [Input](https://ui.jarv.is/components/input.md) and
[Select](https://ui.jarv.is/components/select.md).

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

const sizes = ["sm", "default", "lg"] as const;

export default function TimeInputSizes() {
  return (
    <div className="flex flex-wrap items-center gap-3">
      {sizes.map((size) => (
        <TimeInput key={size} size={size} defaultValue="09:30" aria-label={`Time, ${size}`} />
      ))}
    </div>
  );
}
```

### Invalid

Set `invalid` on the `Field`, and explain the problem with a `FieldError`.

```tsx
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { TimeInput } from "@/components/ui/time-input";

export default function TimeInputInvalid() {
  return (
    <Field invalid className="w-48">
      <FieldLabel>Checkout</FieldLabel>
      <TimeInput defaultValue="15:00" className="w-full" />
      <FieldError>Check out by 11:00 AM.</FieldError>
    </Field>
  );
}
```

### Disabled

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

export default function TimeInputDisabled() {
  return <TimeInput disabled defaultValue="12:00" aria-label="Lunch time" />;
}
```

## Props

Children render at the end of the input, where [Time Picker](https://ui.jarv.is/components/time-picker.md) puts the
button that opens its list. The file also exports `parseTime` and `formatTime`, which parse and
format values in the `HH:mm` format.

| Part | Extends |
| --- | --- |
| `TimeInput` | `<div>` |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### TimeInput

| Prop             | Type                                                                           | Default        | Description                                                                                                                                                                               |
| ---------------- | ------------------------------------------------------------------------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value?`         | `string \| null`                                                               | —              | The time as 24-hour `HH:mm`, or `HH:mm:ss` with `granularity="second"`. `null` when there's none.                                                                                         |
| `defaultValue?`  | `string \| null`                                                               | `null`         |                                                                                                                                                                                           |
| `onValueChange?` | `((value: string \| null, eventDetails: TimeInputChangeEventDetails) => void)` | —              | Called when every part of the time is filled in, and with `null` when a part is cleared. Calling `eventDetails.cancel()` keeps the previous time.                                         |
| `hourCycle?`     | `12 \| 24`                                                                     | `The locale's` | Whether hours run from 1 to 12 with AM and PM, or from 0 to 23.                                                                                                                           |
| `granularity?`   | `"minute" \| "second"`                                                         | `"minute"`     | The smallest part of the time that users can set.                                                                                                                                         |
| `min?`           | `string`                                                                       | —              | The earliest time, as `HH:mm`. Earlier times are invalid. A `min` after `max` makes a range that runs past midnight.                                                                      |
| `max?`           | `string`                                                                       | —              | The latest time, as `HH:mm`. Later times are invalid.                                                                                                                                     |
| `locale?`        | `string`                                                                       | `"en-US"`      | The locale, as a BCP 47 tag, which sets the hour cycle and the AM and PM labels.                                                                                                          |
| `labels?`        | `TimeInputLabels`                                                              | —              | Replaces the parts' accessible names and the validation messages. Pass only the ones you want to change.                                                                                  |
| `name?`          | `string`                                                                       | —              | The name the value is submitted under in a form.                                                                                                                                          |
| `form?`          | `string`                                                                       | —              | The `id` of the form to submit the value with, when the input isn't inside it.                                                                                                            |
| `required?`      | `boolean`                                                                      | `false`        | Whether the form can't be submitted without a time. A time outside `min` and `max` also blocks submission.                                                                                |
| `disabled?`      | `boolean`                                                                      | `false`        | Whether the input is disabled. A disabled `Field` disables it too.                                                                                                                        |
| `readOnly?`      | `boolean`                                                                      | `false`        | Whether the time is shown without letting users change it.                                                                                                                                |
| `size?`          | `"default" \| "lg" \| "sm"`                                                    | `"default"`    | The height: `sm` 24px, `default` 28px, `lg` 32px.                                                                                                                                         |
| `children?`      | `React.ReactNode`                                                              | —              | Content rendered after the time, such as a button that opens a popup.                                                                                                                     |
| `className?`     | `string`                                                                       | —              | CSS class applied to the element.                                                                                                                                                         |
| `style?`         | `React.CSSProperties`                                                          | —              | Style applied to the element.                                                                                                                                                             |
| `render?`        | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement`                       | —              | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### TimeInputLabels

`labels` takes any of these, and keeps the English default for the rest.

| Property      | Type                                     | Default                    | Description                                                                                                         |
| ------------- | ---------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `hour?`       | `string`                                 | `"Hour"`                   | The hour part's accessible name.                                                                                    |
| `minute?`     | `string`                                 | `"Minute"`                 | The minute part's accessible name.                                                                                  |
| `second?`     | `string`                                 | `"Second"`                 | The second part's accessible name, with `granularity="second"`.                                                     |
| `period?`     | `string`                                 | `"AM/PM"`                  | The AM or PM part's accessible name.                                                                                |
| `empty?`      | `string`                                 | `"Empty"`                  | What screen readers announce for an empty part.                                                                     |
| `incomplete?` | `string`                                 | `"Enter a complete time."` | The validation message for a partly typed time.                                                                     |
| `outOfRange?` | `((min: string, max: string) => string)` | —                          | Returns the validation message for a time outside `min` and `max`, given both formatted for the locale.             |
| `tooEarly?`   | `((min: string) => string)`              | —                          | Returns the validation message for a time before `min` when there's no `max`, given `min` formatted for the locale. |
| `tooLate?`    | `((max: string) => string)`              | —                          | Returns the validation message for a time after `max` when there's no `min`, given `max` formatted for the locale.  |

### useTimeFormat

`useTimeFormat(locale?, options?)` takes a BCP 47 tag, as `TimeInput`'s `locale` does, and
these options:

| Option       | Type       | Default | Description                                                     |
| ------------ | ---------- | ------- | --------------------------------------------------------------- |
| `hourCycle?` | `12 \| 24` | —       | The hour cycle to format times in, instead of the locale's own. |

It returns:

| Value         | Type                          | Description                                                               |
| ------------- | ----------------------------- | ------------------------------------------------------------------------- |
| `hourCycle`   | `12 \| 24`                    | The hour cycle times are formatted in.                                    |
| `periods`     | `[string, string]`            | The locale's labels for the morning and the afternoon, such as AM and PM. |
| `periodFirst` | `boolean`                     | Whether the locale puts the AM or PM label before the time.               |
| `label`       | `(seconds: number) => string` | Formats a time, in seconds since midnight, for the locale.                |
