处理日历日期、构建月份网格,并按用户的语言读取和格式化日期。
@ui-sdk/core/date 提供日期运算、月份网格、本地化标签,以及供日历和日期输入框使用的解析。
这些辅助函数处理 "2026-10-16" 这样的日期字符串,无需 DOM 即可运行。Calendar 和 Date Picker 使用相同的辅助函数。
字符串形式的日期
真实日期
用 isoDate 构建日期,用 dateParts 读取它的字段。月份从 1 到 12。日期不存在时,两个函数都返回 undefined:
import { dateParts, isISODate, isoDate } from "@ui-sdk/core/date"
isoDate(2026, 10, 16) // "2026-10-16"
isoDate(2026, 2, 30) // undefined
dateParts("2026-10-16") // { year: 2026, month: 10, day: 16 }
isISODate("2026-02-30") // falseimport * as React from "react"
import { dateParts, isISODate, isoDate, toISODate } from "@ui-sdk/core/date"
import {
Field,
FieldControl,
FieldDescription,
FieldLabel,
} from "@ui-sdk/react/field"
import { useLog } from "./log"
const labels = { year: "Year", month: "Month", day: "Day" }
function Example() {
const log = useLog()
const [fields, setFields] = React.useState({
year: "2026",
month: "2",
day: "30",
})
const [picked, setPicked] = React.useState("2026-10-16")
const built = isoDate(
Number(fields.year),
Number(fields.month),
Number(fields.day)
)
const change = (next: typeof fields) => {
setFields(next)
const date = isoDate(
Number(next.year),
Number(next.month),
Number(next.day)
)
log(
`isoDate(${next.year}, ${next.month}, ${next.day}): ${date ?? "no such day"}`
)
}
const pick = (next: string) => {
setPicked(next)
const parts = isISODate(next) ? dateParts(next) : undefined
log(
parts
? `${next}: year ${parts.year}, month ${parts.month}, day ${parts.day}`
: "Pick a date"
)
}
return (
<div data-slot="stack">
<div data-slot="date-field-group">
{(["year", "month", "day"] as const).map((field) => (
<Field key={field} invalid={!built}>
<FieldLabel>{labels[field]}</FieldLabel>
<FieldControl
inputMode="numeric"
value={fields[field]}
onChange={(event) =>
change({ ...fields, [field]: event.target.value })
}
/>
</Field>
))}
</div>
<div data-slot="date-field-group">
<Field>
<FieldLabel>Picked date</FieldLabel>
<FieldControl
type="date"
value={picked}
onChange={(event) => pick(event.target.value)}
/>
</Field>
<button type="button" onClick={() => pick(toISODate(new Date())!)}>
Today
</button>
</div>
</div>
)
}
export { Example }这些字符串使用 YYYY-MM-DD,与 <input type="date"> 的格式相同。有效日期按日期顺序排序,所以 start < end 这样的比较可以直接使用。
要引入已有的值,使用 toISODate。它接受 ISO 字符串、Date,或带有 year、month 和 day 的对象,包括 Temporal.PlainDate:
import { toISODate } from "@ui-sdk/core/date"
toISODate({ year: 2026, month: 10, day: 16 }) // "2026-10-16"
toISODate(new Date()) // Today's date in the runtime's local time zone.Date 表示一个时刻,所以这个转换使用它的本地年、月、日。得到的字符串不带时区。
运算
整日
对于三晚的住宿,在入住日期上加三天:
import { addDays, daysBetween } from "@ui-sdk/core/date"
addDays("2026-12-24", 3) // "2026-12-27"
daysBetween("2026-12-24", "2026-12-27") // 3负数向后移动。运算按整日进行,所以跨过夏令时变化不会多一天或少一天。
用 clampDate 把日期保持在预订季节内。weekday 对周日返回 0,对周六返回 6:
import { clampDate, weekday } from "@ui-sdk/core/date"
clampDate("2026-10-20", "2026-11-01", "2027-01-31") // "2026-11-01"
weekday("2026-12-24") // 4: Thursday.import * as React from "react"
import {
addDays,
clampDate,
daysBetween,
formatDate,
weekday,
} from "@ui-sdk/core/date"
import {
Field,
FieldControl,
FieldDescription,
FieldLabel,
} from "@ui-sdk/react/field"
import { useLog } from "./log"
const season = { min: "2026-11-01", max: "2027-01-31" }
const today = "2026-10-16"
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]
function stay(picked: string, nights: number) {
const checkIn = clampDate(picked || today, season.min, season.max)
return { checkIn, checkOut: addDays(checkIn, nights) }
}
function Example() {
const log = useLog()
const [picked, setPicked] = React.useState("2026-12-24")
const [nights, setNights] = React.useState(3)
const { checkIn, checkOut } = stay(picked, nights)
const change = (nextPicked: string, nextNights: number) => {
setPicked(nextPicked)
setNights(nextNights)
const next = stay(nextPicked, nextNights)
if (next.checkIn !== nextPicked) {
log(`Moved into the season: ${next.checkIn}`)
}
log(
`${days[weekday(next.checkIn)]} to ${days[weekday(next.checkOut)]}, ${daysBetween(today, next.checkIn)} days after ${formatDate(today, "en-US", { month: "short", day: "numeric" })}`
)
}
return (
<div data-slot="stack">
<div data-slot="date-field-group">
<Field>
<FieldLabel>Check-in</FieldLabel>
<FieldControl
type="date"
value={picked}
onChange={(event) => change(event.target.value, nights)}
/>
</Field>
<Field>
<FieldLabel>Nights</FieldLabel>
<FieldControl
type="number"
min={1}
max={14}
value={nights}
onChange={(event) =>
change(picked, Number(event.target.value) || 1)
}
/>
</Field>
</div>
<Field>
<FieldLabel>Check-out</FieldLabel>
<FieldControl type="date" readOnly value={checkOut} data-check-out />
<FieldDescription data-check-in>
Check-in {days[weekday(checkIn)]},{" "}
{formatDate(checkIn, "en-US", { month: "long", day: "numeric" })}
</FieldDescription>
</Field>
</div>
)
}
export { Example }周与月
按月移动时,尽可能保留日。1 月 31 日会变成 2 月 28 日,因为 2 月没有 31 日:
import { addMonths, addYears } from "@ui-sdk/core/date"
addMonths("2026-01-31", 1) // "2026-02-28"
addYears("2028-02-29", 1) // "2029-02-28"需要边界时,使用 startOfWeek 和 endOfWeek,或 startOfMonth 和 endOfMonth。按周的辅助函数接收一周的第一天,周日为 0:
import {
daysInMonth,
endOfMonth,
isSameMonth,
startOfWeek,
} from "@ui-sdk/core/date"
startOfWeek("2026-10-16", 1) // "2026-10-12": Monday.
endOfMonth("2026-02-10") // "2026-02-28"
daysInMonth(2028, 2) // 29
isSameMonth("2026-09-28", "2026-10-04") // falseimport * as React from "react"
import {
addMonths,
addYears,
daysInMonth,
endOfMonth,
endOfWeek,
isSameMonth,
startOfMonth,
startOfWeek,
} from "@ui-sdk/core/date"
function Example() {
const [date, setDate] = React.useState("2026-01-31")
const [weekStartsOn, setWeekStartsOn] = React.useState(1)
const [year, month] = date.split("-").map(Number)
const week = {
start: startOfWeek(date, weekStartsOn),
end: endOfWeek(date, weekStartsOn),
}
const steps: [string, string, () => string][] = [
["month-back", "− Month", () => addMonths(date, -1)],
["month", "+ Month", () => addMonths(date, 1)],
["year", "+ Year", () => addYears(date, 1)],
]
return (
<div data-slot="stack">
<div data-slot="controls">
{steps.map(([value, text, next]) => (
<button
key={value}
type="button"
data-size="sm"
onClick={() => setDate(next())}
>
{text}
</button>
))}
<button
type="button"
data-size="sm"
onClick={() => setDate("2026-01-31")}
>
Reset
</button>
<select
aria-label="Weeks start on"
value={weekStartsOn}
onChange={(event) => setWeekStartsOn(Number(event.target.value))}
>
<option value={0}>Weeks start on Sunday</option>
<option value={1}>Weeks start on Monday</option>
<option value={6}>Weeks start on Saturday</option>
</select>
</div>
<p data-date data-slot="date-value">
{date}
</p>
<dl>
<dt>Week</dt>
<dd data-this-week>
{week.start} to {week.end}
{!isSameMonth(week.start, week.end) && ", across two months"}
</dd>
<dt>Month</dt>
<dd data-this-month>
{startOfMonth(date)} to {endOfMonth(date)}, {daysInMonth(year, month)}{" "}
days
</dd>
</dl>
</div>
)
}
export { Example }月份网格
可供选择的月份
monthGrid 返回由七个 ISO 日期组成的行。相邻月份的日期会填补边缘。用 weekStartsOn 选择一周的第一天:
import { firstDayOfWeek, monthGrid } from "@ui-sdk/core/date"
const weeks = monthGrid("2026-10-01", {
weekStartsOn: firstDayOfWeek("de-DE"),
})
// The first week runs from "2026-09-28" to "2026-10-04".每周渲染一行,每个日期渲染一个按钮。这个示例加入了游走焦点(roving focus),把每个日期当作键。它自定义的 move 在水平方向键时加一天,垂直方向键时加七天。当焦点到达另一个月份时,示例会渲染那个月份。
import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import {
addDays,
addMonths,
firstDayOfWeek,
formatDate,
isSameMonth,
monthGrid,
startOfMonth,
weekdayNames,
type ISODate,
} from "@ui-sdk/core/date"
import { createParts } from "@ui-sdk/react/primitive"
type MonthOptions = {
defaultValue: ISODate
locale: string
}
type MonthState = {
value: ISODate
month: ISODate
focused: string | null
locale: string
}
type MonthRootState = {
title: string
weekdays: string[]
weeks: ISODate[][]
}
const steps: Record<string, number> = {
ArrowUp: -7,
ArrowDown: 7,
ArrowLeft: -1,
ArrowRight: 1,
}
const month = definePrimitive({
name: "month",
options: { defaultValue: "string", locale: "string" },
state: (options: MonthOptions): MonthState => ({
value: options.defaultValue,
month: startOfMonth(options.defaultValue),
focused: null,
locale: options.locale,
}),
sync: (options) => ({ locale: options.locale }),
api: (context) => {
const { store } = context
const roving = createRovingFocus<MonthState, { value: string }>(context, {
slot: "day",
key: "focused",
remember: false,
preferred: (day) => day.key === store.get().value,
claims: (state, day) => day.key === state.value,
move: (event, { from, rtl }) => {
const by = steps[event.key]
return by === undefined
? undefined
: addDays(from.key, rtl && Math.abs(by) === 1 ? -by : by)
},
})
let view: (MonthRootState & { month: ISODate; locale: string }) | undefined
const viewOf = (state: MonthState) => {
if (view?.month !== state.month || view.locale !== state.locale) {
const weekStartsOn = firstDayOfWeek(state.locale)
view = {
month: state.month,
locale: state.locale,
title: formatDate(state.month, state.locale, {
month: "long",
year: "numeric",
}),
weekdays: weekdayNames(state.locale, "short", weekStartsOn),
weeks: monthGrid(state.month, { weekStartsOn }),
}
}
return view
}
return {
roving,
viewOf,
select: (date: ISODate) => store.set({ value: date }),
turn: (by: number) =>
store.set({ month: addMonths(store.get().month, by) }),
keydown(event: KeyboardEvent, el: HTMLElement) {
const moved = roving.keydown(event, el)
if (moved && !isSameMonth(moved.key, store.get().month)) {
store.set({ month: startOfMonth(moved.key) })
}
},
}
},
slots: (slot) => ({
root: slot<{}, MonthRootState>({
state: (state, { api }) => {
const { title, weekdays, weeks } = api.viewOf(state)
return { title, weekdays, weeks }
},
}),
grid: slot({ attrs: () => ({ role: "grid" }) }),
day: slot<{ value: string }, { selected: boolean; outside: boolean }>({
props: { value: "string" },
selects: selects({ focused: ({ key }) => [key, null] }),
state: (state, { key }) => ({
selected: key === state.value,
outside: !isSameMonth(key, state.month),
}),
attrs: (state, part) => ({
type: "button",
role: "gridcell",
tabindex: part.api.roving.tabIndex(state, part),
"aria-selected": String(part.key === state.value),
"aria-label": formatDate(part.key, state.locale),
"data-selected": part.key === state.value ? "" : undefined,
"data-outside": isSameMonth(part.key, state.month) ? undefined : "",
}),
press: ({ api, key }) => api.select(key),
on: { keydown: (event, { el, api }) => api.keydown(event, el!) },
bind: (el, part) => part.api.roving.bind(el, part),
}),
previous: slot({
attrs: () => ({ type: "button" }),
press: ({ api }) => api.turn(-1),
}),
next: slot({
attrs: () => ({ type: "button" }),
press: ({ api }) => api.turn(1),
}),
}),
})
const parts = createParts(month, {
root: "div",
grid: "div",
day: "button",
previous: "button",
next: "button",
})
const Month = parts.Root
const MonthGrid = parts.Grid
const MonthDay = parts.Day
const MonthPrevious = parts.Previous
const MonthNext = parts.Next
function Example() {
const [locale, setLocale] = React.useState("en-US")
return (
<div data-slot="stack">
<select
aria-label="Locale"
value={locale}
onChange={(event) => setLocale(event.target.value)}
>
<option value="en-US">English (US)</option>
<option value="de-DE">Deutsch</option>
</select>
<Month defaultValue="2026-10-16" locale={locale}>
{({ title, weekdays, weeks }) => (
<>
<div data-slot="row">
<MonthPrevious aria-label="Previous month">‹</MonthPrevious>
<span aria-live="polite" data-slot="month-heading">
{title}
</span>
<MonthNext aria-label="Next month">›</MonthNext>
</div>
<MonthGrid aria-label={title}>
<div role="row" data-slot="month-row">
{weekdays.map((name) => (
<span key={name} role="columnheader">
{name}
</span>
))}
</div>
{weeks.map((week) => (
<div key={week[0]} role="row" data-slot="month-row">
{week.map((day) => (
<MonthDay key={day} value={day}>
{Number(day.slice(8))}
</MonthDay>
))}
</div>
))}
</MonthGrid>
</>
)}
</Month>
</div>
)
}
export {
Example,
month,
Month,
MonthDay,
MonthGrid,
MonthNext,
MonthPrevious,
type MonthOptions,
type MonthRootState,
type MonthState,
}贴合月份的周
网格默认有六周,这样相邻的日历高度一致。传入 fixedWeeks: false 只返回该月需要的周:
monthGrid("2026-02-01").length // 6
monthGrid("2026-02-01", { fixedWeeks: false }).length // 4import * as React from "react"
import { formatDate, isSameMonth, monthGrid } from "@ui-sdk/core/date"
const months = ["2026-02-01", "2026-03-01", "2026-08-01"]
function Example() {
const [fixedWeeks, setFixedWeeks] = React.useState(true)
return (
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<input
type="checkbox"
checked={fixedWeeks}
onChange={(event) => setFixedWeeks(event.target.checked)}
/>
Six weeks each
</label>
</div>
<div data-slot="month-sizes-row">
{months.map((month) => (
<div key={month} data-month={month} data-slot="month-sizes-month">
<p>
{formatDate(month, "en-US", { month: "long", year: "numeric" })}
</p>
{monthGrid(month, { fixedWeeks }).map((week) => (
<div key={week[0]} data-week data-slot="month-sizes-week">
{week.map((day) => (
<span
key={day}
data-outside={isSameMonth(day, month) ? undefined : ""}
>
{Number(day.slice(8))}
</span>
))}
</div>
))}
</div>
))}
</div>
</div>
)
}
export { Example }名称与标签
任意语言的名称
传入 locale,为阅读者格式化日期。不传时,这些函数使用运行时的 locale:
import { formatDate, formatDateRange } from "@ui-sdk/core/date"
formatDate("2026-10-16", "de-DE") // "Freitag, 16. Oktober 2026"
formatDate("2026-10-16", "en-US", { month: "long", year: "numeric" }) // "October 2026"
formatDateRange("2026-10-16", "2026-10-20", "en-US") // "Oct 16 – 20, 2026"formatDate 接受 Intl.DateTimeFormat 选项。它的默认值包括星期、日、月和年,这为日期按钮提供了有用的无障碍标签。
日历的标题需要单独获取月份和星期名称。保持星期名称与网格相同的顺序:
import { firstDayOfWeek, monthNames, weekdayNames } from "@ui-sdk/core/date"
const firstDay = firstDayOfWeek("de-DE") // 1: Monday.
const weekdays = weekdayNames("de-DE", "short", firstDay)
const months = monthNames("de-DE")你可以用 pageLocale 获取页面的 locale。firstDayOfWeek 也遵循显式的一周偏好,比如 "en-US-u-fw-mon" 表示周一。
import * as React from "react"
import {
dateFormatter,
firstDayOfWeek,
formatDate,
formatDateRange,
formatDateToParts,
monthNames,
weekdayNames,
} from "@ui-sdk/core/date"
const locales = [
["en-US", "English (US)"],
["en-US-u-fw-mon", "English (US), weeks from Monday"],
["de-DE", "Deutsch"],
["fr-FR", "Français"],
["ja-JP", "日本語"],
["fa-IR", "فارسی"],
]
const date = "2026-10-16"
function Example() {
const [locale, setLocale] = React.useState("en-US")
const first = firstDayOfWeek(locale)
return (
<div data-slot="stack">
<div data-slot="controls">
<select
aria-label="Locale"
value={locale}
onChange={(event) => setLocale(event.target.value)}
>
{locales.map(([value, text]) => (
<option key={value} value={value}>
{text}
</option>
))}
</select>
</div>
<p data-label data-slot="date-label">
{formatDateToParts(date, locale, { month: "long", day: "numeric" }).map(
(part, index) => (
<span key={index} data-type={part.type}>
{part.value}
</span>
)
)}
</p>
<dl>
<dt>Long</dt>
<dd data-long>{formatDate(date, locale)}</dd>
<dt>Range</dt>
<dd data-range>{formatDateRange(date, "2026-10-20", locale)}</dd>
<dt>Week</dt>
<dd data-weekdays>{weekdayNames(locale, "short", first).join(" ")}</dd>
<dt>Months</dt>
<dd data-months>
{monthNames(locale, "short").slice(0, 4).join(", ")}, …
</dd>
<dt>Calendar</dt>
<dd data-calendar>
{dateFormatter(locale, { month: "long" }).resolvedOptions().calendar}
</dd>
</dl>
</div>
)
}
export { Example }需要分别设置样式的标签时,formatDateToParts 返回每个格式化片段及其类型:
import { formatDateToParts } from "@ui-sdk/core/date"
const parts = formatDateToParts("2026-10-16", "en-US", {
month: "long",
day: "numeric",
})
// [{ type: "month", value: "October" }, { type: "literal", value: " " }, { type: "day", value: "16" }]这些辅助函数使用 Intl 并复用它提供的格式化器。它们让月份和日期标签与公历网格保持一致。使用不同月份体系的 locale,比如 Persian,仍使用公历标签;共享这些月份的日历,比如泰国佛历,可以保留自己的年份。dateFormatter(locale, options) 在需要直接使用时暴露缓存的格式化器。
今天
todayDate() 返回代码运行处的今天日期。当日期属于特定地点时,传入时区:
import { todayDate } from "@ui-sdk/core/date"
todayDate()
todayDate("Asia/Tokyo")import * as React from "react"
import { formatDate, todayDate } from "@ui-sdk/core/date"
const zones = [
["Pacific/Auckland", "Auckland"],
["Asia/Tokyo", "Tokyo"],
["Europe/London", "London"],
["America/Los_Angeles", "Los Angeles"],
]
function Example() {
const [mounted, setMounted] = React.useState(false)
React.useEffect(() => setMounted(true), [])
return (
<ul aria-label="Today" data-slot="list">
{zones.map(([zone, city]) => (
<li key={zone} data-slot="row">
{city}
<span data-slot="hint" data-zone={zone}>
{mounted
? formatDate(todayDate(zone), "en-US", { dateStyle: "medium" })
: ""}
</span>
</li>
))}
<li data-slot="row">
Here
<span data-slot="hint" data-zone="here">
{mounted
? formatDate(todayDate(), "en-US", { dateStyle: "medium" })
: ""}
</span>
</li>
</ul>
)
}
export { Example }服务端渲染(SSR)时,在服务器和客户端传入相同的时区,或等到组件挂载后再标记今天。
输入日期
读取用户输入的内容
parseDate 读取 locale 的日期顺序,返回 ISO 日期。输入不完整或无效时返回 undefined:
import { parseDate } from "@ui-sdk/core/date"
parseDate("10/16/2026", "en-US") // "2026-10-16"
parseDate("16.10.2026", "de-DE") // "2026-10-16"
parseDate("16 oct 2026", "fr") // "2026-10-16"
parseDate("Feb 30", "en-US") // undefined点、斜杠和空格都可以作分隔符。解析器还接受 ISO 日期、月份名称、locale 数字,以及不带分隔符的数字,比如德语中的 "16102026"。
年份缺失时,解析器使用参考日期的年份。参考日期默认是当前年份。如果结果需要保持可预测,传入 referenceDate:
parseDate("October 16", "en-US", { referenceDate: "2026-01-01" }) // "2026-10-16"
parseDate("16.10.70", "de-DE", { referenceDate: "2026-01-01" }) // "1970-10-16"
parseDate("16.10.70", "de-DE", { referenceDate: "2060-01-01" }) // "2070-10-16"两位年份落在 100 年的窗口内,窗口到参考年份之后 20 年为止。
import * as React from "react"
import { datePattern, formatDate, parseDate } from "@ui-sdk/core/date"
import {
Field,
FieldControl,
FieldDescription,
FieldLabel,
} from "@ui-sdk/react/field"
import { useLog } from "./log"
const locales = [
["en-US", "English (US)"],
["de-DE", "Deutsch"],
["fr-FR", "Français"],
["ar-EG", "العربية"],
]
function Example() {
const log = useLog()
const [locale, setLocale] = React.useState("en-US")
const [text, setText] = React.useState("10/16/26")
const [reference, setReference] = React.useState("2026-10-16")
const pattern = datePattern(locale)
const read = (next: {
locale?: string
text?: string
reference?: string
}) => {
const options = { locale, text, reference, ...next }
const date = parseDate(options.text, options.locale, {
referenceDate: options.reference,
})
log(
`“${options.text}”: ${date ? `${date}, ${formatDate(date, options.locale)}` : "not a date"}`
)
}
return (
<div data-slot="stack">
<div data-slot="controls">
<select
aria-label="Locale"
value={locale}
onChange={(event) => {
setLocale(event.target.value)
read({ locale: event.target.value })
}}
>
{locales.map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
<input
type="date"
aria-label="Reference date"
value={reference}
onChange={(event) => {
const next = event.target.value || "2026-10-16"
setReference(next)
read({ reference: next })
}}
/>
</div>
<Field>
<FieldLabel>Date</FieldLabel>
<FieldControl
placeholder={pattern.placeholder}
value={text}
onChange={(event) => {
setText(event.target.value)
read({ text: event.target.value })
}}
/>
<FieldDescription data-pattern>
{pattern.fields.join(` ${pattern.separator} `)}
</FieldDescription>
</Field>
</div>
)
}
export { Example }用 datePattern 生成输入框的占位符和显示顺序的提示:
import { datePattern } from "@ui-sdk/core/date"
const pattern = datePattern("de-DE")
pattern.fields // ["day", "month", "year"]
pattern.placeholder // "TT.MM.JJJJ"
pattern.separator // "."
// pattern.example is December 31 in the current year, written in this locale.API 参考
这些函数都来自 @ui-sdk/core/date。