본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Time Field (시간 필드)

원문 보기 위키 갱신

TimeField는 네이티브 <input type="time">의 대안으로, 시간을 더 유연하고 자유롭게 선택할 수 있게 해 주는 컴포넌트예요. 시·분·초 같은 세그먼트로 나뉘어 있고 로케일과 표기 방식도 다양하게 다룰 수 있습니다. 값을 다루기 전에 Bits UI의 날짜·시간 개념부터 확인하면 좋아요.

출처: 문서

본문

<script lang="ts">
  import { TimeField } from "bits-ui";
</script>
<TimeField.Root>
  <div class="flex w-full max-w-[280px] flex-col gap-1.5">
    <TimeField.Label class="block select-none text-sm font-medium"
      >Appointment Time</TimeField.Label
    >
    <TimeField.Input
      name="hello"
      class="h-input rounded-input border-border-input bg-background text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-invalid:border-destructive flex w-full select-none items-center border px-2 py-3 text-sm tracking-[0.01em] "
    >
      {#snippet children({ segments })}
        {#each segments as { part, value }, i (part + i)}
          <div class="inline-block select-none">
            {#if part === "literal"}
              <TimeField.Segment {part} class="text-muted-foreground p-1">
                {value}
              </TimeField.Segment>
            {:else}
              <TimeField.Segment
                {part}
                class="rounded-5px hover:bg-muted focus:bg-muted focus:text-foreground aria-[valuetext=Empty]:text-muted-foreground data-invalid:text-destructive focus-visible:ring-0! focus-visible:ring-offset-0! px-1 py-1"
              >
                {value}
              </TimeField.Segment>
            {/if}
          </div>
        {/each}
      {/snippet}
    </TimeField.Input>
  </div>
</TimeField.Root>
참고!

이 컴포넌트를 자세히 살펴보기 전에, Bits UI에서 날짜/시간이 어떻게 동작하는지 이해하는 게 중요해요. 더 알고 싶다면 Dates/Times 문서를 먼저 읽어 주세요!

개요

TimeField 컴포넌트는 네이티브 <input type="time"> 요소의 대안이에요. 지정된 필드 안에서 시간을 더 유연하고 커스터마이즈 가능한 방식으로 선택할 수 있게 해 줍니다.

구조

<script lang="ts">
  import { TimeField } from "bits-ui";
</script>
<TimeField.Root>
  <TimeField.Label>Check-in time</TimeField.Label>
  <TimeField.Input>
    {#snippet children({ segments })}
      {#each segments as { part, value }}
        <TimeField.Segment {part}>
          {value}
        </TimeField.Segment>
      {/each}
    {/snippet}
  </TimeField.Input>
</TimeField.Root>

재사용 가능한 컴포넌트

애플리케이션 전반에서 쓸 수 있는 커스텀 시간 필드 컴포넌트를 만들 때는 TimeField 프리미티브를 사용하는 걸 권장해요.

다음 예시는 애플리케이션 전반에서 재사용할 수 있는 MyTimeField 컴포넌트를 만드는 방법을 보여줘요. 스타일 아이디어는 이 페이지 상단의 데모를 참고하면 됩니다.

MyTimeField.svelte

<script lang="ts" module>
  import type { TimeValue } from "bits-ui";
  import type { Time } from "@internationalized/date";
  type T = unknown;
</script>
<script lang="ts" generics="T extends TimeValue = Time">
  import { TimeField, type WithoutChildrenOrChild } from "bits-ui";
  let {
    value = $bindable(),
    placeholder = $bindable(),
    labelText = "Select a time",
    ...restProps
  }: WithoutChildrenOrChild<TimeField.RootProps<T>> & {
    name?: string;
    labelText?: string;
  } = $props();
</script>
<TimeField.Root bind:value bind:placeholder {...restProps}>
  <TimeField.Label {name}>{labelText}</TimeField.Label>
  <TimeField.Input>
    {#snippet children({ segments })}
      {#each segments as { part, value }}
        <TimeField.Segment {part}>
          {value}
        </TimeField.Segment>
      {/each}
    {/snippet}
  </TimeField.Input>
</TimeField.Root>

코드 펼치기

<script lang="ts" module>
  import type { TimeValue } from "bits-ui";
  import type { Time } from "@internationalized/date";
  type T = unknown;
</script>
<script lang="ts" generics="T extends TimeValue = Time">
  import { TimeField } from "bits-ui";
  let {
    labelText = "Select a time",
    value = $bindable(),
    placeholder = $bindable(),
    name,
    ...restProps
  }: TimeField.RootProps<T> & { labelText?: string; name?: string } = $props();
</script>
<TimeField.Root bind:value bind:placeholder {...restProps}>
  <div class="flex w-fit min-w-[280px] flex-col gap-1.5">
    <TimeField.Label class="block select-none text-sm font-medium"
      >{labelText}</TimeField.Label
    >
    <TimeField.Input
      {name}
      class="h-input rounded-input border-border-input bg-background text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-invalid:border-destructive flex w-full select-none items-center border px-2 py-3 text-sm tracking-[0.01em] "
    >
      {#snippet children({ segments })}
        {#each segments as { part, value }, i (i)}
          <div class="inline-block select-none">
            {#if part === "literal"}
              <TimeField.Segment {part} class="text-muted-foreground p-1">
                {value}
              </TimeField.Segment>
            {:else}
              <TimeField.Segment
                {part}
                class="rounded-5px hover:bg-muted focus:bg-muted focus:text-foreground aria-[valuetext=Empty]:text-muted-foreground data-invalid:text-destructive focus-visible:ring-0! focus-visible:ring-offset-0! px-1 py-1"
              >
                {value}
              </TimeField.Segment>
            {/if}
          </div>
        {/each}
      {/snippet}
    </TimeField.Input>
  </div>
</TimeField.Root>

이제부터 나오는 데모와 예시에서는 같은 코드를 반복하지 않기 위해 방금 만든 MyTimeField 컴포넌트를 사용할 거예요. 문서를 읽으며 필요하면 이 컴포넌트를 함께 참고하세요.

세그먼트 (Segments)

TimeField의 세그먼트는 hour, minute, second, dayPeriod, timeZoneName 같은 특정 시간 부분만 나타내는 게 아니에요. 시간의 각 부분 사이를 구분하는 "literal"(리터럴)도 참조하는데, 이 리터럴은 보통 구분 기호이며 locale에 따라 달라집니다.

아까 만든 MyTimeField 컴포넌트를 보면, "literal"인지 여부에 따라 TimeField.Segment 컴포넌트에 다른 스타일을 적용한 걸 볼 수 있어요.

Placeholder

TimeField.Root 컴포넌트의 placeholder prop은 필드가 비었을 때 표시되는 값이 아니라, 사용자가 세그먼트들을 순환할 때 필드가 시작해야 하는 시간을 뜻해요.

기본적으로 placeholder는 시간 순환 방식에 따라 12:00 AM 또는 00:00으로 설정돼요.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import { Time } from "@internationalized/date";
</script>
<MyTimeField placeholder={new Time(12, 30)} />

시간대도 함께 표시하고 싶다면 ZonedDateTime 객체를 사용하면 돼요.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import { now, getLocalTimeZone } from "@internationalized/date";
</script>
<MyTimeField placeholder={now("America/New_York")} />

placeholder 상태 다루기

이번 절에서는 Time Field의 placeholder 상태를 어떻게 관리하는지 다뤄요.

양방향 바인딩 (Two-Way Binding)

간단하고 자동적인 상태 동기화를 위해 bind:placeholder를 사용해요:

<script lang="ts">
  import { TimeField } from "bits-ui";
  import { Time } from "@internationalized/date";
  let myPlaceholder = $state(new Time(12, 30));
</script>
<button onclick={() => (myPlaceholder = new Time(12, 30))}>
  Set placeholder to 12:30 PM
</button>
<TimeField.Root bind:placeholder={myPlaceholder}>
  <!-- ... -->
</TimeField.Root>

완전 제어 (Fully Controlled)

상태의 읽기와 쓰기를 완전히 통제하고 싶다면 Function Binding을 사용해요.

<script lang="ts">
  import { TimeField, type TimeValue } from "bits-ui";
  let myPlaceholder = $state<TimeValue>();
  function getPlaceholder() {
    return myPlaceholder;
  }
  function setPlaceholder(newPlaceholder: TimeValue) {
    myPlaceholder = newPlaceholder;
  }
</script>
<TimeField.Root bind:placeholder={getPlaceholder, setPlaceholder}>
  <!-- ... -->
</TimeField.Root>

value 상태 다루기

이번 절에서는 Time Field의 value 상태를 어떻게 관리하는지 다뤄요. value는 Time, CalendarDateTime, ZonedDateTime 객체가 될 수 있고, value/onValueChange prop의 타입은 value prop의 타입을 보고 추론됩니다.

양방향 바인딩 (Two-Way Binding)

간단하고 자동적인 상태 동기화를 위해 bind:value를 사용해요:

<script lang="ts">
  import { TimeField } from "bits-ui";
  import { Time } from "@internationalized/date";
  let myValue = $state(new Time(12, 30));
</script>
<button onclick={() => (myValue = myValue.add({ hours: 1 }))}>
  Add 1 hour
</button>
<TimeField.Root bind:value={myValue}>
  <!-- ... -->
</TimeField.Root>

완전 제어 (Fully Controlled)

컴포넌트 상태를 완전히 통제하려면 Function Binding으로 value 상태를 외부에서 관리해요.

<script lang="ts">
  import { TimeField, type TimeValue } from "bits-ui";
  let myValue = $state<TimeValue>();
  function getValue() {
    return myValue;
  }
  function setValue(newValue: TimeValue | undefined) {
    myValue = newValue;
  }
</script>
<DateField.Root bind:value={getValue, setValue}>
  <!-- ... -->
</DateField.Root>

기본값

흔히 TimeField.Root 컴포넌트를 기본값으로 시작하게 하고 싶을 거예요. 그 값은 보통 ISO 8601 문자열 형태로 데이터베이스에서 오죠. @internationalized/date 패키지의 parseDateTime 함수로 그 문자열을 CalendarDateTime 객체로 파싱할 수 있습니다.

+page.svelte

<script lang="ts">
  import { TimeField } from "bits-ui";
  import { parseDateTime } from "@internationalized/date";
  // this came from a database/API call
  const date = "2024-08-03T15:15";
  let value = $state(parseDateTime(date));
</script>
<TimeField.Root {value}>
  <!-- ... -->
</TimeField.Root>

이제 우리 입력 필드에 기본값이 채워져요. parseDateTime 외에도 시간대를 다룬다면 parseZonedDateTime으로 문자열을 ZonedDateTime 객체로 파싱할 수 있습니다.

유효성 검사

최솟값

minValue prop으로 TimeField.Root 컴포넌트의 최솟값을 설정할 수 있어요. 사용자가 최솟값보다 작은 시간을 선택하면 시간 필드가 잘못된(invalid) 상태로 표시됩니다.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import { Time } from "@internationalized/date";
</script>
<MyTimeField minValue={new Time(9, 0)} value={new Time(8, 0)} />

위 예시에서는 최솟값을 9:00 AM, 기본값을 8:00 AM으로 설정했어요. 그래서 시간 필드가 invalid로 표시되고, 그에 맞게 스타일을 줄 수 있습니다. 시간을 최솟값보다 크게 조정하면 invalid 상태는 사라져요.

최댓값

maxValue prop으로 TimeField.Root 컴포넌트의 최댓값을 설정할 수 있어요. 사용자가 최댓값보다 큰 시간을 선택하면 시간 필드가 invalid로 표시됩니다.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import { Time } from "@internationalized/date";
</script>
<MyTimeField maxValue={new Time(17, 0)} value={new Time(18, 0)} />

위 예시에서는 최댓값을 5:00 PM, 기본값을 6:00 PM으로 설정했어요. 그래서 시간 필드가 invalid로 표시되고, 그에 맞게 스타일을 줄 수 있습니다. 시간을 최댓값보다 작게 조정하면 invalid 상태는 사라져요.

커스텀 유효성 검사

validate prop으로 시간 필드에 커스텀 유효성 검사 함수를 제공할 수 있어요. 이 함수는 시간이 잘못됐을 때 검증 오류로 문자열이나 문자열 배열을, 유효하면 undefined나 아무것도 반환하지 않아야 합니다.

그 문자열들은 onInvalid 콜백으로 전달되는데, 이 콜백으로 사용자에게 오류 메시지를 표시할 수 있어요.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import type { TimeValue } from "bits-ui";
  import { Time } from "@internationalized/date";
  import { toast } from "your-favorite-toast-library";
  const value = new Time(12, 30);
  function validate(time: TimeValue) {
    return time.hour === 12 ? "Time cannot be 12:00 PM" : undefined;
  }
  function onInvalid(
    reason: "min" | "max" | "custom",
    msg?: string | string[]
  ) {
    if (reason === "custom") {
      if (typeof msg === "string") {
        // do something with the error message
        toast.error(msg);
        return;
      } else if (Array.isArray(msg)) {
        // do something with the error messages
        toast.error(msg.join(", "));
        return;
      }
      toast.error("The time is invalid");
    } else if (reason === "min") {
      // let the user know that the date is too early.
      toast.error("The time is too early.");
    } else if (reason === "max") {
      // let the user know that the date is too late.
      toast.error("The date is too late.");
    }
  }
</script>
<MyTimeField {validate} {value} {onInvalid} />

세밀도 (Granularity)

granularity prop은 날짜 필드의 세밀도를 설정해서, 날짜 필드에 어떤 세그먼트가 렌더링될지 결정해요. granularity는 'hour', 'minute', 'second' 중 하나로 설정할 수 있고 기본값은 'minute'입니다.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
  import { Time } from "@internationalized/date";
  const value = new Time(12, 30);
</script>
<MyTimeField granularity="second" {value} />

위 예시에서는 granularity를 'second'로 설정했어요. 그래서 시간 필드에 초(second)를 위한 세그먼트가 추가됩니다.

지역화 (Localization)

locale prop으로 날짜 필드의 로케일을 설정할 수 있어요. 이 값은 날짜 필드의 세그먼트와 placeholder의 표기 방식에 영향을 줍니다.

<script lang="ts">
  import MyTimeField from "$lib/components/MyTimeField.svelte";
</script>
<MyTimeField locale="de" value={new Time(13, 30, 0)} />

위 예시를 보면 로케일이 de(독일어)로 설정되어 있어서, 시(hour)가 24시간 형식의 13으로 표시되고 오전/오후(day period)는 표시되지 않는 걸 볼 수 있어요.

API 참조

TimeField.Root

루트 시간 필드 컴포넌트예요.

Property Type Description Details
value $bindable TimeValue - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time | CalendarDateTime | ZonedDateTime The selected time.Default:  —— undefined
onValueChange function - (value: TimeValue) => void A function that is called when the selected time changes. The type of value is inferred from the value prop if provided.Default:  —— undefined
placeholder $bindable TimeValue - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time | CalendarDateTime | ZonedDateTime The placeholder time, which is used to determine what time to start the segments from when no value exists.Default:  —— undefined
onPlaceholderChange function - (value: TimeValue) => void A function that is called when the placeholder time changes.Default:  —— undefined
required boolean Whether or not the field is required.Default: false
validate function - (time: TimeValue) => string[] | string | void A function that returns whether or not a time is unavailable.Default:  —— undefined
onInvalid function - (reason: 'min' | 'max' | 'custom', msg?: string | string[]) => void A callback fired when the field's value is invalid.Default:  —— undefined
errorMessageId string The id of the element which contains the error messages for the field when the time is invalid.Default:  —— undefined
hourCycle enum - '12' | '24' The hour cycle to use for formatting times. Defaults to the locale preferenceDefault:  —— undefined
granularity enum - 'hour' | 'minute' | 'second' The granularity to use for formatting the field. The field will render segments for each part of the time up to and including the specified granularity.Default: 'minute'
hideTimeZone boolean Whether or not to hide the time zone segment of the field. This only applies when using a ZonedDateTime as the value prop.Default: false
maxValue TimeValue - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time | CalendarDateTime | ZonedDateTime The maximum valid time that can be entered.Default:  —— undefined
minValue TimeValue - import type { Time, CalendarDateTime, ZonedDateTime } from "@internationalized/date"; type TimeValue = Time | CalendarDateTime | ZonedDateTime The minimum valid time that can be entered.Default:  —— undefined
locale string The locale to use for formatting times.Default: en-US
disabled boolean Whether or not the field is disabled.Default: false
readonly boolean Whether or not the field is readonly.Default: false
readonlySegments EditableTimeSegmentPart[] - "hour" | "minute" | "second" | "dayPeriod" An array of segments that should be readonly, which prevent user input on them.Default:  —— undefined
children Snippet The children content to render.Default:  —— undefined

TimeField.Input

시간 필드의 세그먼트들을 감싸는 컨테이너예요.

Property Type Description Details
name string The name of the time field used for form submission. If provided, a hidden input element will be rendered alongside the time field.Default:  —— undefined
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet - import type { TimeSegmentPart } from "bits-ui" type TimeFieldInputChildrenSnippetProps = { segments: Array<{ part: TimeSegmentPart; value: string }> } The children content to render.Default:  —— undefined
child Snippet - import type { TimeSegmentPart } from "bits-ui" type ChildSnippetProps = { props: Record<string, unknown> segments: Array<{ part: TimeSegmentPart; value: string }> } Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid.
data-disabled '' Present on the element when the field is disabled.
data-time-field-input '' Present on the element.

TimeField.Segment

시간 필드의 세그먼트예요.

Property Type Description Details
part required TimeSegmentPart - "hour" | "minute" | "second" | "dayPeriod" | "timeZoneName" | "literal"; The part of the time to render.Default:  —— undefined
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid
data-disabled '' Present on the element when the field is disabled
data-readonly '' Present on the element when the field or segment is readonly
data-segment enum - 'hour' | 'minute' | 'second' | 'dayPeriod' | 'timeZoneName' | 'literal' The part of the time to render.
data-time-field-segment '' Present on the element.

TimeField.Label

시간 필드의 라벨이에요.

Property Type Description Details
ref $bindable HTMLSpanElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-invalid '' Present on the element when the field is invalid
data-disabled '' Present on the element when the field is disabled
data-time-field-label '' Present on the element.

더 알아보기 (Learn more)

TimeField는 날짜·시간 계열 컴포넌트라 Dates/Times 문서와 함께 보는 걸 권장해요. granularity, locale, 검증 기능까지 조합하면 시간 입력을 정밀하게 제어할 수 있어, 예약이나 스케줄 화면에 잘 어울립니다.