逐段输入日期,顺序跟随用户语言的写法。

把 Date Input 用于人们记在心里的日期,比如生日或预订日期。日期的每一部分都是一个独立的小输入框,顺序按 locale 的写法排列。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Start date</FieldLabel>
      <DateInput />
    </Field>
  )
}

export { Example }
点击月份并输入 11042026。每一部分填满后都会移到下一部分。在某个部分上按 ArrowUp 或 ArrowDown,可以按步进调整它。

安装

npm install @ui-sdk/react @ui-sdk/core

组合

用下面的组合构建 DateInput:

DateInput
├── DateInputSegment
└── DateInputSegment

DateInput 渲染一个分组,日期的每一部分对应一个 DateInputSegment:英语里是月、日、年,德语里是日、月、年。你输入的每个分段都是一个小输入框。它们之间的斜杠或点也是分段,只是纯文本。DateInput 会替你渲染分段;只有想改变它们的外观时才自己渲染,参见自定义渲染。

用法

把输入框放进 Field,并给它一个标签:

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Start date</FieldLabel>
      <DateInput defaultValue="2026-11-02" />
    </Field>
  )
}

export { Example }

值是 "2026-11-02" 这样的 ISO 日期字符串,和原生日期输入框一样。在每个分段都填入内容之前,它一直是 null,因此你的应用只会看到完整日期。

输入数字,每个分段填满后移到下一个。像 4 这样不能再接一位数字的月份,会立即移到下一个。输入分隔符,比如 / 或 .,也会移到下一个。日会被限制在当月之内:从 1 月 31 日移到 2 月,显示的是 28 日。把完整日期粘贴到任意分段,可以是 2026-11-02,也可以是 locale 的写法。

字段

字段的标签为这个分组提供名称,点击标签会把焦点移到第一个分段。它的描述会和输入框一起被读出。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Birthday</FieldLabel>
      <DateInput name="birthday" />
      <FieldDescription>We send a card on the day.</FieldDescription>
    </Field>
  )
}

export { Example }
点击 Birthday 把焦点移到月份,然后输入日期。屏幕阅读器会把描述和输入框一起读出。

日期与时间

把 granularity 设为 "hour"、"minute" 或 "second",就能加上时间。值会变成 "2026-11-02T14:30" 这样的本地日期和时间。只要时间,请用 Time Input。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Departure</FieldLabel>
      <DateInput granularity="minute" defaultValue="2026-11-02T14:30" />
    </Field>
  )
}

export { Example }
用 Tab 依次经过日期和时间。在最后一个分段输入 P 或 A,可以在 AM 和 PM 之间切换。

最小与最大

min 和 max 接受 ISO 日期。超出范围的日期无效:输入框会设置 data-invalid,它的表单也不会提交。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Check-in</FieldLabel>
      <DateInput min="2026-01-01" max="2026-12-31" defaultValue="2026-06-15" />
      <FieldDescription>Any day in 2026.</FieldDescription>
      <FieldError />
    </Field>
  )
}

export { Example }
把 Check-in 的年份改成 2027,看它变为无效,再改回 2026。

不可用的日期

unavailable 接受与 Calendar 相同的匹配器:ISO 日期、{ from, to } 范围、{ weekday: [0, 6] } 这样的星期,或一个函数。不可用的日期无效,并以“This date isn't available.”作为消息。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Delivery date</FieldLabel>
      <DateInput defaultValue="2026-11-02" unavailable={{ weekday: [0, 6] }} />
      <FieldDescription>We deliver Monday to Friday.</FieldDescription>
      <FieldError />
    </Field>
  )
}

export { Example }
把 Delivery date 的日往回步进,从 2 日星期一退到 1 日星期日。在你重新选到工作日之前,输入框一直无效。

语言

输入框从 locale 读取顺序、分隔符和时钟,省略时读取页面的语言。数字始终是 0 到 9,日历始终是公历,所以这个值在任何地方都表示同一个日期。在服务器上,输入框会先以英语渲染,直到读到页面的语言;如果首次渲染很重要,请设置 locale。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <div data-slot="stack">
      <Field>
        <FieldLabel>Date (en-GB)</FieldLabel>
        <DateInput locale="en-GB" defaultValue="2026-11-02" />
      </Field>
      <Field>
        <FieldLabel>Datum (de-DE)</FieldLabel>
        <DateInput locale="de-DE" defaultValue="2026-11-02" />
      </Field>
      <Field>
        <FieldLabel>日付 (ja-JP)</FieldLabel>
        <DateInput locale="ja-JP" defaultValue="2026-11-02" />
      </Field>
    </div>
  )
}

export { Example }
同一个日期在英式英语、德语和日语中的样子。每种语言都按自己的方式排列各部分。

禁用

在输入框上,或在它的 Field 或 fieldset 上设置 disabled,可以让它无法获得焦点,也不参与表单。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Start date</FieldLabel>
      <DateInput defaultValue="2026-11-02" disabled />
    </Field>
  )
}

export { Example }
点击 Start date,或按 Tab 试着移到它上面。焦点会跳过它,日期保持 2026 年 11 月 2 日。

只读

设置 readOnly,得到一个可以聚焦、读取,并按原样提交的日期。

"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Signed on</FieldLabel>
      <DateInput defaultValue="2026-11-02" readOnly />
    </Field>
  )
}

export { Example }
聚焦 Signed on,按 ArrowUp 或输入一个数字。日期保持不变。

表单

隐藏的输入框会以 name 提交 ISO 日期。空日期或只输入了一部分的日期会提交空字符串。设置 required 后,表单需要先有日期才能提交。在分段中按 Enter 会用已输入的内容提交表单。

控制台
"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldError, FieldLabel } from "@ui-sdk/react/field"
import { TimeInput } from "@ui-sdk/react/time-input"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        const data = [...new FormData(event.currentTarget)].map(
          ([name, value]) => `${name}=${value}`
        )
        log(`Submitted ${data.join(", ")}`)
      }}
    >
      <Field>
        <FieldLabel>Date</FieldLabel>
        <DateInput name="date" defaultValue="2026-11-02" required />
        <FieldError />
      </Field>
      <Field>
        <FieldLabel>Time</FieldLabel>
        <TimeInput name="time" defaultValue="09:30" required />
        <FieldError />
      </Field>
      <div data-slot="row">
        <button type="reset">Reset</button>
        <button type="submit" data-variant="solid">
          Book
        </button>
      </div>
    </form>
  )
}

export { Example }
用 Backspace 清空 Date 的日,然后选择 Book,看表单停止提交。填好后再选择 Book:控制台会记录这些值。Reset 会恢复默认值。

只输入了一部分的日期也会阻止表单提交,并以“Enter a valid date.”作为消息。把 form 设为页面中另一个表单的 id,就能用那个表单提交和校验。表单重置会恢复 defaultValue,并报告 reset 原因。

受控

传入 value,并在 onValueChange 中更新它。回调会在得到每个完整日期时运行,在日期的任意部分被擦除后则以 null 运行。只输入了一半的日期本身就读作 null,所以把值设为 null 会保持已输入的内容。调用控制器上的 clear() 可以清空每个分段。

控制台
"use client"

import { DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import * as React from "react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [value, setValue] = React.useState<string | null>("2026-11-02")

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => setValue(null)}>
          Clear
        </button>
      </div>
      <Field>
        <FieldLabel>Due date</FieldLabel>
        <DateInput
          value={value}
          onValueChange={(next) => {
            setValue(next)
            log(`Due date ${next ?? "empty"}`)
          }}
        />
      </Field>
    </div>
  )
}

export { Example }
修改 Due date:控制台会记录每个完整日期。Clear 会把值设为 null。

共享约定见状态与事件,每次变更的原因见原因。

控制器

用 createDateInputController() 创建控制器,并作为 controller 传入,就能从别处设置、清空或聚焦输入框。focus("year") 按单位聚焦某个分段。

"use client"

import { createDateInputController, DateInput } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import * as React from "react"

function Example() {
  const [publish] = React.useState(createDateInputController)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => publish.setValue("2026-12-25")}>
          Christmas
        </button>
        <button type="button" onClick={() => publish.focus("year")}>
          Edit Year
        </button>
        <button type="button" onClick={() => publish.clear()}>
          Clear
        </button>
      </div>
      <Field>
        <FieldLabel>Publish on</FieldLabel>
        <DateInput controller={publish} />
      </Field>
    </div>
  )
}

export { Example }
选择 Christmas 设置日期,选择 Edit Year 聚焦年份,或选择 Clear 清空它。

控制器涵盖了创建和共享控制器。

自定义渲染

把函数作为 children 传入,自己渲染分段。函数会收到输入框的状态,其中的 segments 按顺序列出每个分段,以及它们之间的文本。为每个分段渲染一个 DateInputSegment,并给分段之间的文本传入你自己的 children。

"use client"

import { DateInput, DateInputSegment } from "@ui-sdk/react/date-input"
import { Field, FieldLabel } from "@ui-sdk/react/field"

function Example() {
  return (
    <Field>
      <FieldLabel>Start date</FieldLabel>
      <DateInput defaultValue="2026-11-02">
        {({ segments }) =>
          segments.map((segment) =>
            segment.editable ? (
              <DateInputSegment key={segment.key} segment={segment} />
            ) : (
              <DateInputSegment key={segment.key} segment={segment}>
                –
              </DateInputSegment>
            )
          )
        }
      </DateInput>
    </Field>
  )
}

export { Example }
这里的分段之间用短横线代替 locale 的斜杠。顺序仍按 locale 的。

你输入内容的分段渲染一个 <input>,分段之间的文本渲染一个 <span>。只有当 segment.editable 为 true 时,才把 input 交给 render。

每个部件的状态列在状态下。

样式

把根部件当作字段的外框来设置样式,分段则放在其中。每个分段都会把 data-type 设成它的单位,所以你可以加宽年份,或弱化分段之间的文本,后者带有 data-type="literal"。空的分段会设置 data-empty 并显示占位符。日期超出范围或不可用时,根部件会设置 data-invalid。

每个部件都有一个 data-slot,比如 date-input-segment,它的状态属性列在数据属性下。

数据属性

DateInput

[data-slot="date-input"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-invalidPresent while the date is before min, after max or unavailable.
data-emptyPresent while every segment is empty.

DateInputSegment

[data-slot="date-input-segment"]

属性含义
data-typeyearmonthdayhourminuteseconddayPeriodliteralThe segment's unit, or literal for the text between segments.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-invalidPresent while the date is before min, after max or unavailable.
data-emptyPresent while the segment is empty. It shows its placeholder.

API 参考

属性和回调与下面相同,都作为 React props。

DateInput

value?string | null
The value: an ISO date like "2026-11-02", with a time granularity a date and time like "2026-11-02T14:30", or null. Pass it to control the input.
defaultValue?string | null
The value it starts with, when uncontrolled, and goes back to when its form resets.
onValueChange?((value: string | null, details: ChangeDetails<DateInputValueChangeReason>) => void)
Runs when the value wants to change: once every segment holds something, and again with null when one is emptied. details.cancel() keeps the value.
granularity?DateInputGranularity
The smallest unit it shows. "day" shows a date, and "hour", "minute" or "second" add the time down to it.
hourCycle?HourCycle
A 12 or 24 hour clock for the time. Defaults to the locale's.
min?string
The earliest value, as an ISO date or date and time. A value before it is invalid.
max?string
The latest value. A date alone takes any time that day. A value after it is invalid.
unavailable?DateMatchers
Dates that can't be chosen, as in Calendar: ISO dates, { from, to } ranges, weekdays or a function. A value on one is invalid.
locale?string
The language whose order, separators and clock it shows. Defaults to the page's.
disabled?boolean
Whether it can't be used.
readOnly?boolean
Whether the value can be seen but not changed.
required?boolean
Whether a value must be entered before its form submits.
name?string
The name the value submits under.
form?string
The id of the form it belongs to, when it isn't inside it.
controller?object
Drives it from anywhere. Create one with createDateInputController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

DateInputSegment

segmentDateInputSegmentData
The segment it shows, from the root's segments.

状态

渲染函数、基于状态的类名和 children 会收到什么。

valuestring | null
The value, or null while empty or partly filled.
segmentsDateInputSegmentData[]
The segments in the order the locale shows them, with the text between them. Render one part for each.
disabledboolean
Whether it can't be used, by itself or by a <fieldset>.
readOnlyboolean
Whether the value can be seen but not changed.
invalidboolean
Whether the value is before min, after max or an unavailable date.

每个分段的状态 DateInputSegmentState,是分段本身加上它旁边的输入框状态:

keystring
Tells segments apart: the type, or "literal-<n>" for the text between them.
typeDateInputSegmentType
textstring
What it shows: the number, padded, or AM and PM in the locale. Empty while it holds nothing.
valuenumber | null
The number it holds, or null while empty. AM is 0 and PM is 1.
minnumber
The smallest number it takes.
maxnumber
The largest number it takes, like the days in the month.
emptyboolean
Whether it holds nothing yet.
editableboolean
Whether it's a segment you type in, rather than the text between segments.
labelstring
Its name in the locale, like "month", which names it to assistive technology.
disabledboolean
Whether it can't be used.
readOnlyboolean
Whether its value can't be changed.
invalidboolean
Whether the value is before min, after max or an unavailable date.

原因

details.reason 说明值为什么改变。

input-changeEvent
Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
step-keyKeyboardEvent
Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
pasteClipboardEvent
Files were pasted, like a screenshot, or text and tokens into a token input.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

控制器

用 createDateInputController() 创建一个,并作为 controller 传入。

每个写入方法都接受可选的 { reason, event },像输入一样运行变更回调,并在变更被取消时返回 false。

getValue()() => string | null
The value, or null while empty or partly filled.
setValue(value, options?)(value: string | null, options?: DateInputChangeOptions | undefined) => boolean
Sets the value. Returns false when it isn't a value the input can show, or when canceled.
clear(options?)(options?: DateInputChangeOptions | undefined) => boolean
Empties every segment.
focus(segment?)(segment?: string | undefined) => void
Focuses a segment, like "month", or the first one.

事件

回调先收到新值,然后收到详情。

属性所属收到
onValueChangeDateInput(value, details):ISO 日期(被擦除后为 null),以及原因

无障碍

根部件是一个分组,名称来自它的 Field 标签或你的 aria-label。每个分段都是一个 spinbutton,由它的单位命名,比如“month”,并带有它的值、范围和文本。空的分段读作“Empty”。分段之间的文本对屏幕阅读器隐藏,屏幕阅读器改为读取每个分段的名称。

分段是真正的输入框,所以手机显示数字键盘,页面脚本运行之前的输入也能生效。

键盘

按键动作
0 到 9填充分段,然后移到下一个。
ArrowUp / ArrowDown让分段步进一个值,越界时循环。空的分段从今天开始。
PageUp / PageDown用更大的步进移动:年每次 5,月每次 3,日每次 7,分钟每次 15。
Home / End跳到分段的第一个或最后一个值。
ArrowLeft / ArrowRight移到前一个或后一个分段。
Backspace删除最后一位数字,然后清空分段,再往回移动。
Delete清空分段。
A / P在 12 小时制的时间里选择 AM 或 PM。
Enter用已输入的内容提交表单。
Tab / Shift+Tab依次经过各个分段,然后离开输入框。

在从右到左的页面中,分段保持 locale 的顺序,ArrowLeft 和 ArrowRight 跟随屏幕上的顺序。

经过测试的行为

下面每一行都是一个自动化测试。

  • Each unit is a spinbutton in the locale's order.
  • Another locale orders the segments its own way.
  • Typing fills each segment, moves on and reports the date once.
  • A press on the box or between segments focuses the nearest segment.
  • A digit that can't start a longer number moves on at once.
  • A separator moves to the next segment.
  • Typing with separators over a filled date or time keeps every segment.
  • ArrowUp and ArrowDown step a segment and wrap around.
  • PageUp and PageDown take bigger steps.
  • Home and End go to a segment's first and last values.
  • ArrowLeft and ArrowRight move between segments.
  • Tab moves through the segments, then out.
  • Backspace empties a segment, then moves back.
  • A day past the end of a new month is moved back to its last day.
  • Pasting a date fills every segment.
  • A time takes hours, minutes and AM or PM.
  • A 24-hour clock has no AM or PM.
  • A date with a time shows its hour and minute too.
  • A controller sets and clears the date.
  • A canceled change keeps the date.
  • The form submits the ISO date and time under their names.
  • Enter submits the form with what was typed.
  • Enter submits a form with no submit button, in a segment or the form's one text field.
  • Resetting the form brings back the default date.
  • A partly filled date can't be submitted.
  • A required empty date can't be submitted.
  • A date after max is invalid.
  • An unavailable date is invalid.
  • The field's label focuses the first segment.
  • A native label for the input focuses the first segment wherever it's pressed. 仅在 Web components 运行。
  • A read-only date takes focus but doesn't change.
  • A disabled date can't be focused.
  • Digits committed through an input method fill the segment.

运行于 React、Vue 和 web components。