DatePicker

基于国际化标准的日期选择器组件。
查看源码

简介

MDatePicker 是一个国际化日期选择器,基于 @internationalized/date 处理时区与本地化。支持单日期、日期范围、多日期选择,并提供按钮触发、可清空、快捷预设等多种交互形态。

基于 Nuxt UI 的 Calendar 组件封装
使用 @internationalized/date 库进行日期处理,确保时区安全和国际化支持。

用法

默认按钮触发器展示当前日期,点击打开日历面板后选择并写入 v-model:

<script setup lang="ts">
const value = ref("")
</script>

<template>
  <MDatePicker />
</template>

range 日期范围

range 模式维护 start / end 两端日期,numberOfMonths 可同时展示双月日历:

<script setup lang="ts">
const value = ref("")
</script>

<template>
  <MDatePicker range :number-of-months="2" />
</template>

numberOfMonths 月份数量

numberOfMonths 控制弹层内并排展示的月份数量,便于跨月选择:

<template>
  <MDatePicker :number-of-months="3" />
</template>

clearable 可清空

clearable 在已有值时显示清除入口,点击后重置且不展开日历:

<template>
  <MDatePicker clearable />
</template>

presets 快捷预设

presets 设为 default 会按当前模式自动生成「今天」「本周」「本月」等快捷项:

<template>
  <MDatePicker range presets="default" />
</template>

multiple 多日期选择

multiple 模式将多个日期保存在数组中,按钮文案可根据已选数量动态展示:

<template>
  <MDatePicker multiple :button-props="{ label: '选择多个日期', color: 'primary' }" />
</template>

buttonProps 触发按钮

buttonProps 透传给触发按钮,可调整 label、color、variant 与 icon:

<template>
  <MDatePicker
    :button-props="{
      label: '选择生日',
      color: 'primary',
      variant: 'outline',
      icon: 'i-lucide-cake'
    }"
  />
</template>

示例

继承字段上下文

放入 UFormField 后继承 size 与错误态,触发按钮按表单状态渲染:

示例错误态
<script setup lang="ts">
defineProps<{
  size: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
}>()
</script>

<template>
  <UFormField label="预约日期" :size="size" error="示例错误态">
    <MDatePicker />
  </UFormField>
</template>

融入UFieldGroup

与按钮置于 UFieldGroup 时共用尺寸与边框衔接,适合筛选栏中组合快捷操作:

<script setup lang="ts">
defineProps<{
  size: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
}>()
</script>

<template>
  <UFieldGroup :size="size">
    <MDatePicker />
    <UButton icon="i-lucide-calendar-check" color="neutral" variant="subtle" />
  </UFieldGroup>
</template>

限制可选日期边界

minValue 与 maxValue 会禁用边界外日期,分别约束只能选择未来或过去日期:

<script setup lang="ts">
import type { CalendarDate } from '#movk/types'

const formatter = useDateFormatter()
const futureDate = shallowRef<CalendarDate>()
const pastDate = shallowRef<CalendarDate>()
</script>

<template>
  <div class="space-y-4">
    <UFormField label="未来日期">
      <MDatePicker
        v-model="futureDate"
        :min-value="formatter.getToday()"
        :button-props="{ label: '选择未来日期', class: 'w-full' }"
      />
    </UFormField>

    <UFormField label="过去日期">
      <MDatePicker
        v-model="pastDate"
        :max-value="formatter.getToday()"
        :button-props="{ label: '选择过去日期', class: 'w-full' }"
      />
    </UFormField>
  </div>
</template>

按规则禁用日期

isDateUnavailable 可按业务规则禁用日期(如示例中的周末):

<script setup lang="ts">
import { CalendarDate } from '#movk/composables/useDateFormatter'
import type { DateValue } from '#movk/types'

const formatter = useDateFormatter()
const date = shallowRef(new CalendarDate(2025, 11, 18))

// 禁用周末
const isDateUnavailable = (date: DateValue) => {
  return formatter.isWeekend(date)
}
</script>

<template>
  <MDatePicker
    v-model="date"
    :is-date-unavailable="isDateUnavailable"
    :button-props="{ label: '仅工作日', class: 'w-full' }"
  />
</template>

自定义触发按钮文案

labelFormat 接收格式化工具和当前值,可把日期与星期信息组合为按钮 label:

<script setup lang="ts">
import { CalendarDate } from '@internationalized/date'

const isoDate = shallowRef(new CalendarDate(2025, 11, 18))
const timestampDate = shallowRef(new CalendarDate(2025, 11, 18))
const customDate = shallowRef(new CalendarDate(2025, 11, 18))
</script>

<template>
  <div class="space-y-4">
    <UFormField label="ISO 格式">
      <MDatePicker v-model="isoDate" label-format="iso" :button-props="{ class: 'w-full' }" />
    </UFormField>

    <UFormField label="时间戳">
      <MDatePicker v-model="timestampDate" label-format="timestamp" :button-props="{ class: 'w-full' }" />
    </UFormField>

    <UFormField label="自定义">
      <MDatePicker
        v-model="customDate"
        :button-props="{ class: 'w-full' }"
        :label-format="(fmt, value) => {
          if (!value || !fmt.isDateValue(value)) return '选择日期'
          return `${fmt.format(value)} (星期${fmt.getDayOfWeek(value)})`
        }"
      />
    </UFormField>
  </div>
</template>

自定义快捷预设

presets 传入数组可按业务规则返回日期,每项 value 是接收 formatter 的函数:

<script setup lang="ts">
import type { DateValue } from '@movk/nuxt'

const value = shallowRef<DateValue>()
</script>

<template>
  <MDatePicker
    v-model="value"
    placeholder="选择日期"
    :presets="[
      { label: '本周一', value: f => f.getStartOfWeek(f.getToday()) as DateValue },
      { label: '本月初', value: f => f.getStartOfMonth(f.getToday()) as DateValue },
      { label: '本年初', value: f => f.getStartOfYear(f.getToday()) as DateValue }
    ]"
  />
</template>

useDateFormatter

用法

使用自动导入的 useDateFormatter composable 进行日期格式化、转换和操作,基于 @internationalized/date 库实现国际化日期处理。

<script setup lang="ts">
const formatter = useDateFormatter({ locale: 'zh-CN' })

const today = formatter.getToday()
const formattedDate = formatter.format(today)
// "2025年11月29日"

const isoString = formatter.toISO(today)
// "2025-11-29"
</script>
  • useDateFormatter 基于 Intl.DateTimeFormat 提供本地化日期格式化。
  • 支持单个日期、日期范围、日期数组以及嵌套对象的批量转换。
  • 通过 timeZone 选项指定时区(默认本地时区),标识符遵循 IANA 时区数据库规范。
所有格式化和转换方法都内置了错误处理,当传入 null 或 undefined 时会返回空字符串或 null,避免抛出异常。

能力一览

下表覆盖了 useDateFormatter 在常用日期场景下的输出形态:

当前 locale: zh-CN · timeZone: UTC

调用返回值
format(today)
2026年11月23日
toISO(today)
2026-11-23
toTimestamp(today)
1795392000000
toUnixTimestamp(today)
1795392000
isWeekend(today)
false
isWeekday(today)
true
isToday(today)
true
getDayOfWeek(today)
0
getDayOfWeekName(today, "long")
星期一
getDayOfWeekName(today, "short")
周一
getStartOfMonth(today)
2026-11-01
getEndOfMonth(today)
2026-11-30
getStartOfYear(today)
2026-01-01
getEndOfYear(today)
2026-12-31
formatRange(start, end)
2026年11月23日 - 2026年11月30日
formatArray([d, d+1, d+2])
2026年11月23日, 2026年11月24日, 2026年11月25日
parse("2026-01-01")?.toString()
2026-01-01
<script setup lang="ts">
const f = useDateFormatter({ locale: 'zh-CN' })
const today = f.getToday()
const range = { start: today, end: today.add({ days: 7 }) }
const list = [today, today.add({ days: 1 }), today.add({ days: 2 })]

const rows = [
  { method: 'format(today)', value: f.format(today) },
  { method: 'toISO(today)', value: f.toISO(today) },
  { method: 'toTimestamp(today)', value: f.toTimestamp(today) },
  { method: 'toUnixTimestamp(today)', value: f.toUnixTimestamp(today) },
  { method: 'isWeekend(today)', value: f.isWeekend(today) },
  { method: 'isWeekday(today)', value: f.isWeekday(today) },
  { method: 'isToday(today)', value: f.isToday(today) },
  { method: 'getDayOfWeek(today)', value: f.getDayOfWeek(today) },
  { method: 'getDayOfWeekName(today, "long")', value: f.getDayOfWeekName(today, 'long') },
  { method: 'getDayOfWeekName(today, "short")', value: f.getDayOfWeekName(today, 'short') },
  { method: 'getStartOfMonth(today)', value: f.toISO(f.getStartOfMonth(today)) },
  { method: 'getEndOfMonth(today)', value: f.toISO(f.getEndOfMonth(today)) },
  { method: 'getStartOfYear(today)', value: f.toISO(f.getStartOfYear(today)) },
  { method: 'getEndOfYear(today)', value: f.toISO(f.getEndOfYear(today)) },
  { method: 'formatRange(start, end)', value: f.formatRange(range.start, range.end) },
  { method: 'formatArray([d, d+1, d+2])', value: f.formatArray(list) },
  { method: 'parse("2026-01-01")?.toString()', value: f.parse('2026-01-01')?.toString() ?? 'null' }
]

const columns = [
  { accessorKey: 'method', header: '调用' },
  { accessorKey: 'value', header: '返回值' }
]
</script>

<template>
  <div class="flex flex-col gap-3">
    <p class="text-xs text-muted">
      当前 locale: {{ f.locale }} · timeZone: {{ f.timeZone }}
    </p>
    <MDataTable :columns="columns" :data="rows" stripe bordered density="compact" />
  </div>
</template>

与 AutoForm 集成

在 AutoForm 中使用日期字段时,建议使用 convertToISO() 进行批量转换后提交:

<script setup lang="ts">
const { afz } = useAutoForm()
const formatter = useDateFormatter()

const schema = afz.object({
  eventDate: afz.calendarDate(),
  eventRange: afz.calendarDate({
    controlProps: { mode: 'range' }
  })
})

const formData = ref()

async function handleSubmit() {
  // 自动处理所有日期字段的转换
  const payload = formatter.convertToISO(formData.value)

  // payload.eventDate: "2025-11-29"
  // payload.eventRange: { start: "2025-11-01", end: "2025-11-30" }

  await api.submit(payload)
}
</script>
convertToISO 自动遍历所有嵌套日期字段并保持对象结构不变,无需手动转换。

API

useDateFormatter()

useDateFormatter(options?: DateFormatterOptions): DateFormatter

创建日期格式化器实例。

Parameters
options
DateFormatterOptions
日期格式化配置选项。
Returns

返回包含以下方法和属性的日期格式化器对象。

格式化方法

format()
(date: DateValue | undefined | null) => string
格式化单个日期为本地化字符串。
formatRange()
(start: DateValue | undefined | null, end: DateValue | undefined | null, separator?: string) => string
格式化日期范围,默认分隔符为 ' - '。
formatArray()
(dates: DateValue[] | undefined | null, separator?: string) => string
格式化日期数组,默认分隔符为 ', '。

转换方法

toISO()
(date: DateValue | undefined | null) => string
转换为 ISO 8601 字符串。
toDate()
(date: DateValue | undefined | null) => Date | null
转换为 JavaScript Date 对象。
toTimestamp()
(date: DateValue | undefined | null) => number | null
转换为时间戳(毫秒)。
toUnixTimestamp()
(date: DateValue | undefined | null) => number | null
转换为 Unix 时间戳(秒)。
parse()
(value: string) => DateValue | null
解析 ISO 8601 日期字符串。自动识别 CalendarDate、CalendarDateTime 或 ZonedDateTime。

工具方法 - 获取日期

getToday()
() => CalendarDate
获取今天的日期。
getNow()
() => ZonedDateTime
获取当前日期时间。
getStartOfWeek()
(date: DateValue) => DateValue
获取一周的开始日期(基于当前语言区域)。
getEndOfWeek()
(date: DateValue) => DateValue
获取一周的结束日期(基于当前语言区域)。
getStartOfMonth()
(date: DateValue) => DateValue
获取一月的开始日期。
getEndOfMonth()
(date: DateValue) => DateValue
获取一月的结束日期。
getStartOfYear()
(date: DateValue) => DateValue
获取一年的开始日期。
getEndOfYear()
(date: DateValue) => DateValue
获取一年的结束日期。

工具方法 - 查询

getDayOfWeek()
(date: DateValue) => number
获取星期几数字(0-6,0 为本地化的一周第一天)。
getDayOfWeekName()
(date: DateValue, style?: 'narrow' | 'short' | 'long') => string
获取本地化的星期几名称。
getWeeksInMonth()
(date: DateValue) => number
获取本月的周数。
isWeekday()
(date: DateValue) => boolean
判断是否为工作日。
isWeekend()
(date: DateValue) => boolean
判断是否为周末。
isSameDay()
(a: DateValue, b: DateValue) => boolean
判断是否为同一天。
isSameMonth()
(a: DateValue, b: DateValue) => boolean
判断是否为同一月。
isSameYear()
(a: DateValue, b: DateValue) => boolean
判断是否为同一年。
isToday()
(date: DateValue) => boolean
判断是否为今天。
isDateValue()
(value: unknown) => value is DateValue
类型守卫,判断是否为 DateValue 类型。
isDateRange()
(value: unknown) => value is DateRange
类型守卫,判断是否为 DateRange 类型。

批量转换方法

convertData()
<T>(data: T, converter: (value: DateValue) => any) => T
通用数据转换函数,自动处理单个日期、日期范围、日期数组以及嵌套对象。
convertToISO()
<T>(data: T) => T
批量转换为 ISO 字符串。支持单个日期、日期范围、数组和嵌套对象。
convertToFormatted()
<T>(data: T) => T
批量转换为格式化字符串。
convertToDate()
<T>(data: T) => T
批量转换为 Date 对象。

配置属性

locale
string
当前使用的语言区域。
timeZone
string
当前使用的时区。

Changelog

No recent changes

控制日历开关

v-model:open 同步弹层状态,也可调用实例的 open() 和 close()。旧 popoverProps.open 作为次级控制,popoverProps.defaultOpen 只用于初始化非受控状态。

<script setup lang="ts">
const open = ref(false)
const picker = useTemplateRef('picker')
</script>

<template>
  <div class="flex flex-wrap items-center gap-2">
    <UButton label="Open calendar" @click="picker?.open()" />
    <MDatePicker ref="picker" v-model:open="open" />
    <UButton label="Close calendar" variant="outline" @click="picker?.close()" />
  </div>
</template>

API

Props

Prop Default Type
as'div'any

The element or component this component should render as.

id string
name string
size "xs" | "sm" | "md" | "lg" | "xl"

同时作用于触发按钮与日历,缺省时继承 UFormField / UFieldGroup

color "primary" | "secondary" | "info" | "success" | "warning" | "error" | "important" | "neutral"

日历主色;处于表单错误态时触发按钮显示为 error

disabledboolean
placeholder string

未选择时的按钮文本,缺省时依次取 buttonProps.label、locale 的 datePicker.placeholder

buttonProps ButtonProps
popoverProps PopoverProps<P>
labelFormat'formatted' "iso" | "timestamp" | "unix" | "date" | "formatted" | (formatter: { format: (date: Nullable<DateValue>) => string; formatRange: (start: Nullable<DateValue>, end: Nullable<DateValue>, separator?: string) => string; ... 38 more ...; timeZone: string; }, modelValue: CalendarModelValue<...> | undefined): string
valueFormat'date-value' V

v-model 投影输出格式

clearableboolean
presets "default" | DatePickerPreset<R, M>[]

快捷预设

locale string

语言区域,缺省时跟随 <UApp :locale>,组件外调用时为 'en'

formatOptions Intl.DateTimeFormatOptions

日期格式化选项

timeZone string

时区标识符,默认使用本地时区

type'date' "date" | "month" | "year"

The type of picker.

  • date renders a day calendar whose heading can switch to a month then year view.
  • month renders a standalone month picker.
  • year renders a standalone year picker.
nextYearIconappConfig.ui.icons.chevronDoubleRightany

The icon to use for the next year control.

nextYear Omit<ButtonProps, LinkPropsKeys>

Configure the next year button. { color: 'neutral', variant: 'ghost' }

nextMonthIconappConfig.ui.icons.chevronRightany

The icon to use for the next month control.

nextMonth Omit<ButtonProps, LinkPropsKeys>

Configure the next month button. { color: 'neutral', variant: 'ghost' }

prevYearIconappConfig.ui.icons.chevronDoubleLeftany

The icon to use for the previous year control.

prevYear Omit<ButtonProps, LinkPropsKeys>

Configure the prev year button. { color: 'neutral', variant: 'ghost' }

prevMonthIconappConfig.ui.icons.chevronLeftany

The icon to use for the previous month control.

prevMonth Omit<ButtonProps, LinkPropsKeys>

Configure the prev month button. { color: 'neutral', variant: 'ghost' }

viewControltrueboolean | Omit<ButtonProps, LinkPropsKeys>

Whether to make the heading a button that switches between the day, month and year views. Has no effect when type is year. Can be an object to override the button props. { color: 'neutral', variant: 'ghost', block: true }

variant'solid' "solid" | "outline" | "soft" | "subtle"
range R

Whether or not a range of dates can be selected

multiple M

Whether or not multiple dates can be selected

monthControlsboolean

Show month controls

yearControlsboolean

Show year controls

defaultValue CalendarDefaultValue<R, M>
weekNumbersboolean
defaultPlaceholder CalendarDate | CalendarDateTime | ZonedDateTime

The default placeholder date

allowNonContiguousRangesboolean

When combined with isDateUnavailable, determines whether non-contiguous ranges, i.e. ranges containing unavailable dates, may be selected.

pagedNavigationboolean

This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month

preventDeselectboolean

Whether or not to prevent the user from deselecting a date without selecting another date first

maximumDays number

The maximum number of days that can be selected in a range

weekStartsOn 0 | 1 | 2 | 4 | 5 | 3 | 6

The day of the week to start the calendar on

weekdayFormat "narrow" | "short" | "long"

The format to use for the weekday strings provided via the weekdays slot prop

fixedWeeksboolean

Whether or not to always display 6 weeks in the calendar

maxValue CalendarDate | CalendarDateTime | ZonedDateTime

The maximum date that can be selected

minValue CalendarDate | CalendarDateTime | ZonedDateTime

The minimum date that can be selected

numberOfMonths number

The number of months to display at once

readonlyboolean

Whether or not the calendar is readonly

initialFocusboolean

If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted

isDateDisabled (date: DateValue): boolean

A function that returns whether or not a date is disabled

isDateUnavailable (date: DateValue): boolean

A function that returns whether or not a date is unavailable

isDateHighlightable (date: DateValue): boolean

A function that returns whether or not a date is hightable

nextPage (placeholder: DateValue): DateValue

A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component.

prevPage (placeholder: DateValue): DateValue

A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component.

disableDaysOutsideCurrentViewboolean

Whether or not to disable days outside the current view.

fixedDate "start" | "end"

Which part of the range should be fixed

isMonthDisabled (date: DateValue): boolean

A function that returns whether or not a month is disabled

isMonthUnavailable (date: DateValue): boolean

A function that returns whether or not a month is unavailable

isYearDisabled (date: DateValue): boolean

A function that returns whether or not a year is disabled

isYearUnavailable (date: DateValue): boolean

A function that returns whether or not a year is unavailable

yearsPerPage number

Number of years to display per page

modelValue FormattedValue<R, M, V>
openundefinedboolean
ui Record<string, c> & { content?: SlotClass; arrow?: SlotClass; wrapper?: SlotClass; presets?: SlotClass; presetButton?: SlotClass; calendar?: SlotClass; clearIcon?: SlotClass; }

Emits

Event Type
close:prevent[]
(evt: "close:prevent"): void
update:modelValue[value: FormattedValue<R, M, V>]
(evt: "update:modelValue", value: FormattedValue<R, M, V>): void
update:placeholder[date: DateValue]
(evt: "update:placeholder", date: DateValue): void
update:validModelValue[date: DateRange]
(evt: "update:validModelValue", date: DateRange): void
update:startValue[date: DateValue | undefined]
(evt: "update:startValue", date: DateValue | undefined): void
update:open[value: boolean | undefined]
(event: "update:open", value: boolean | undefined): void
update:modelValue[value: FormattedValue<R, M, V> | undefined]
(event: "update:modelValue", value: FormattedValue<R, M, V> | undefined): void

Slots

Slot Type
default{ open: boolean; }
contentSlotProps<P>
heading{ value: string; view: CalendarView; date: DateValue; setView: (view: CalendarView) => void; setPlaceholder: (date: DateValue) => void; }
dayPick<CalendarCellTriggerProps, "day">
week-day{ day: string; }
month-cell{ month: DateValue; selected: boolean; disabled: boolean; }
year-cell{ year: DateValue; selected: boolean; disabled: boolean; }
leading{ ui: { base: (props?: Record<string, any> | undefined) => string; label: (props?: Record<string, any> | undefined) => string; leadingIcon: (props?: Record<string, any> | undefined) => string; leadingAvatar: (props?: Record<string, any> | undefined) => string; leadingAvatarSize: (props?: Record<string, any> | undefined) => string; trailingIcon: (props?: Record<string, any> | undefined) => string; }; }
trailing{ ui: { base: (props?: Record<string, any> | undefined) => string; label: (props?: Record<string, any> | undefined) => string; leadingIcon: (props?: Record<string, any> | undefined) => string; leadingAvatar: (props?: Record<string, any> | undefined) => string; leadingAvatarSize: (props?: Record<string, any> | undefined) => string; trailingIcon: (props?: Record<string, any> | undefined) => string; }; }

Theme

app.config.ts
export default defineAppConfig({
  ui: {
    datePicker: {
      slots: {
        wrapper: 'flex',
        presets: 'flex flex-col gap-1 p-2 border-r border-default min-w-[120px]',
        presetButton: 'justify-start',
        calendar: 'p-2',
        clearIcon: 'cursor-pointer opacity-60 hover:opacity-100 transition-opacity'
      },
      variants: {
        withPresets: {
          true: {},
          false: {
            wrapper: 'block'
          }
        }
      },
      defaultVariants: {
        withPresets: false
      }
    }
  }
})

Changelog

No recent changes
Copyright © 2025 - 2026 YiXuan - MIT License