Input · TimePicker

TimePicker

Users can easily select a compliant, formatted point of time using the time selector.

Demos

How to import

<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

Basic Usage

Click TimePicker, and then you can select or enter a time in the floating layer.

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<TimePicker />

Infinite Scroll

Starting from version V2.22.0, we changed the default mode of ScrollItem in TimePicker from wheel to normal. If you want to apply the effect of infinite scrolling back, please refer to the following example.

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<TimePicker scrollItemProps={{ mode: 'wheel', cycled: true }} />

Controlled Component

Use bind:value as a controlled component. There is no defaultValue; put the initial value on the bound variable. null is a controlled empty value, and undefined means uncontrolled. Cleared, the value is undefined (single) or an empty array (range).

Code
<script lang="ts">
    import { TimePicker, type TimePickerBaseValueType } from '@fibrae/semi-ui-svelte';

    let value = $state<TimePickerBaseValueType | TimePickerBaseValueType[] | null>(null);
    const onChange = (time: unknown) => console.log(time);
</script>

<TimePicker bind:value {onChange} />

Different Format

The columns in the TimePicker float will follow format Change, when omitted format At some point, the corresponding column in the floating layer will also disappear.

NOTE: format Follow the date-fns v4 format Format. https://date-fns.org/docs/format

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<TimePicker format="HH:mm" value="10:24" />

Disable Time Selection

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<TimePicker disabled value="12:08:23" />

Set Step Length

Available Hour Step, Minute Step, Second Step Show the optional minutes and seconds by step.

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<TimePicker minuteStep={15} secondStep={10} />

12-hour System

12-hour time selector, default format for a h:mm:ss, an incoming format The format must be in dateFns date formatWithin range.

For example, the default 12-hour format string is:a h:mm:ss, if passed in A h:mm:ss This will result in an inability to format correctly.



Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<div>
    <TimePicker use12Hours />
    <br />
    <br />
    <TimePicker format="a h:mm" use12Hours />
</div>

Time Range

Pass type = "timeRange" to enable time range selection.



Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';
</script>

<div>
    <TimePicker type="timeRange" value={['10:23:15', '12:38:32']} />
    <br />
    <br />
    <TimePicker format="a h:mm" type="timeRange" use12Hours value={['上午 08:11', '下午 11:21']} />
</div>

Disable left/right panels in Range mode (disabledTime)

When type="timeRange", you can use disabledTime(value, panelType) to apply different disabled rules for the left/right panel.

  • value: the currently selected times, the unpicked side undefined (e.g. [date, undefined]); an empty array when there is no value, and length 1 when value, defaultValue or the input holds a single time
  • panelType: 'left' | 'right', representing start/end panel

In the following demo, after selecting a start time, the right (end) panel will disable options earlier than the start time.

Code
<script lang="ts">
    import { TimePicker } from '@fibrae/semi-ui-svelte';

    const range = (length: number) => Array.from({ length }, (_, i) => i);

    // The right panel disables everything earlier than the start time picked on the left
    const disabledTime = (value: (Date | undefined)[], panelType: 'left' | 'right') => {
        const start = value[0];
        if (panelType === 'right' && start) {
            const h = start.getHours();
            const m = start.getMinutes();
            return {
                disabledHours: () => range(h),
                disabledMinutes: (hour: number) => (hour === h ? range(m) : []),
            };
        }
        return {};
    };
</script>

<TimePicker {disabledTime} type="timeRange" />

Custom Trigger

By default we use the Input component as the trigger for the TimePicker component. You can customize this trigger with the trigger snippet. It receives { value, inputValue, placeholder, disabled, componentProps, onChange }: the unpicked side of value is undefined, and onChange updates the input text, as typing would.

Code
<script lang="ts">
    import * as dateFns from 'date-fns';
    import { IconTimePicker } from '@fibrae/semi-icons-svelte/lab';
    import { Tag, TimePicker, type TimePickerBaseValueType } from '@fibrae/semi-ui-svelte';

    const formatToken = 'HH:mm:ss';
    let time = $state<TimePickerBaseValueType | TimePickerBaseValueType[] | null>(new Date(2024, 0, 1, 10, 30, 0));
</script>

<TimePicker bind:value={time} format={formatToken}>
    {#snippet trigger({ placeholder })}
        <Tag color="cyan" shape="circle" size="large" style="padding: 12px; padding-right: 16px; font-size: 14px" type="light">
            {#snippet prefixIcon()}
                <IconTimePicker />
            {/snippet}
            {time instanceof Date ? dateFns.format(time, formatToken) : placeholder}
        </Tag>
    {/snippet}
</TimePicker>

TimeZone Config

Semi All configuration about time zone is converged in ConfigProvider

Select Time Zone:


TimePicker:
Code
<script lang="ts">
    import { ConfigProvider, Select, TimePicker } from '@fibrae/semi-ui-svelte';

    let timeZone = $state('GMT+08:00');
    const defaultTimestamp = 1581599305265;
    const gmtList: string[] = [];
    for (let hourOffset = -11; hourOffset <= 14; hourOffset++) {
        const prefix = hourOffset >= 0 ? '+' : '-';
        gmtList.push(`GMT${prefix}${String(Math.abs(hourOffset)).padStart(2, '0')}:00`);
    }
    const optionList = gmtList.map((gmt) => ({ value: gmt, label: gmt }));

    const onChange = (date: unknown, dateString: string | string[]) => console.log('DatePicker changed: ', date, dateString);
</script>

<ConfigProvider {timeZone}>
    <div style="width: 300px">
        <h5 style="margin: 10px">Select Time Zone:</h5>
        <Select aria-label="时区" onSelect={(value) => (timeZone = String(value))} {optionList} placeholder="请选择时区" showClear style="width: 300px" value={timeZone} />
        <br />
        <br />
        <h5 style="margin: 10px">TimePicker:</h5>
        <TimePicker {onChange} value={defaultTimestamp} />
    </div>
</ConfigProvider>

API Reference

Props

PropertyDescriptionTypeDefault
autoAdjustOverflowWhether to flip the popup automatically when it is clipped.booleantrue
autofocusFocuses the input on mount, which opens the panel.booleanfalse
borderlessBorderless mode.booleanfalse
clearIconCustom clear icon; effective when showClear is true.Snippet-
disabledDisables all interaction.boolean-
disabledHoursReturns the hours that cannot be selected.Type() => number[]-
disabledMinutesReturns the minutes that cannot be selected for the selected hour.Type(selectedHour: number) => number[]-
disabledSecondsReturns the seconds that cannot be selected for the selected hour and minute.Type(selectedHour: number, selectedMinute: number) => number[]-
disabledTimeRange mode only: returns the disabled rules of the left and right panel from the current value and the panel. The unpicked side of value is undefined; a returned disabledHours, disabledMinutes or disabledSeconds overrides the prop of the same name, and one left out falls back to it.Type(value: (Date | undefined)[], panelType: PanelType) => DisabledTimeFns-
focusOnOpenFocuses the input and selects its content once mounted, which opens the panel.booleanfalse
formatDisplay format, following date-fns format. Defaults to a h:mm:ss with use12Hours, else HH:mm:ss.string-
hideDisabledOptionsHides the options that cannot be selected.booleanfalse
hourStepInterval of the hour options; a positive integer.number-
inputReadOnlyMakes the input read-only, which avoids opening the virtual keyboard on mobile devices.booleanfalse
inputStyleStyle of the input's root element.string-
insetLabelInset label of the input.Snippet-
insetLabelIdid of the insetLabel, referenced through aria-labelledby.string-
minuteStepInterval of the minute options; a positive integer.number-
motionWhether the popup animates.booleantrue
onBlurCalled when a click outside closes the panel, with the native event of that mousedown; leaving the input does not call it.Type(event: MouseEvent) => void-
onChangeCalled when the time changes, with (Date value, formatted string); both are arrays in range mode. Cleared, it is undefined (single) or an empty array (range); the unpicked side of a range is undefined.Type(value: Date | (Date | undefined)[] | undefined, str: string | string[]) => void-
onEnterPressCalled when Enter is pressed in the input.Type(event: KeyboardEvent) => void-
onFocusCalled when the input's root element gains focus; moving focus between the input and the clear button does not call it.Type(event: FocusEvent) => void-
onKeyDownkeydown callback of the input.Type(event: KeyboardEvent) => void-
onKeyUpkeyup callback of the input.Type(event: KeyboardEvent) => void-
onOpenChangeCalled when the panel opens or closes.Type(open: boolean) => void-
openWhether the panel is open, used with bind:open; undefined means uncontrolled.boolean-
panelRange mode only: used as both the header and the footer of panel index, taking precedence over panelHeader and panelFooter while it has content.TypeSnippet<[TimePickerPanelSnippetProps]>-
panelFooterSnippet for the content below the panel; index is the panel's position.TypeSnippet<[TimePickerPanelSnippetProps]>-
panelHeaderSnippet for the content above the panel; index is the panel's position (0 for time, 0 or 1 for timeRange). Without it, a range shows the locale's start and end text.TypeSnippet<[TimePickerPanelSnippetProps]>-
placeholderHint shown without a value; defaults to the locale text of type.string-
popupClassNameClass name of the popup.ClassValue-
popupStyleStyle of the popup, as a string.string-
positionPopup position. Defaults to bottom when type is timeRange, and bottomLeft when it is time.Position-
prefixPrefix content of the input.Snippet-
preventScrollWhether the browser should scroll the document to show the newly focused element; applies to the focus call inside the component.boolean-
rangeSeparatorSeparator between the two times of a range.string" ~ "
scrollItemPropsProps passed to the columns; only cycled, mode, motion and transform, as on the ScrollItem of ScrollList.TimePickerScrollItemProps-
secondStepInterval of the second options; a positive integer.number-
showClearWhether to show the clear button.booleantrue
sizeSize of the input.InputSize-
stopPropagationWhether to stop click events on the popup from bubbling.booleantrue
timeZoneTime zone; falls back to the timeZone of ConfigProvider, then to the global default.string | number-
triggerSnippet of a custom trigger that replaces the default input; a click anywhere in it opens the panel. Receives value (the unpicked side undefined), inputValue, placeholder, disabled, componentProps and onChange (updates the input text, as typing would).TypeSnippet<[TimePickerTriggerRenderProps]>-
typeSelection type: time for a single time, timeRange for a range.TimePickerType"time"
use12HoursUses the 12-hour clock.booleanfalse
validateStatusValidation status.ValidateStatus-
valueCurrent time, used with bind:value; an array when type is timeRange. null is a controlled empty value, and undefined means uncontrolled.TimePickerBaseValueType | TimePickerBaseValueType[] | null-

Methods

MethodDescriptionType
blurRemoves focus from the input; does nothing with a custom trigger.Type() => void
focusFocuses the input, which opens the panel; does nothing with a custom trigger.Type() => void

Of the undeclared attributes, class and style land on the root element, and the others (id, title, aria-*, data-*, native events and so on) land on the inner input; with the trigger snippet they land on no element and are available through componentProps.

Call focus() and blur() on the component instance; they do nothing with a custom trigger.

Accessibility

ARIA

  • The input has the role combobox with aria-haspopup="dialog", an aria-expanded that follows the panel, and aria-controls pointing at the panel
  • The hour, minute, second and AM/PM columns are listbox lists named "Hour", "Minute", "Second" and "AM/PM"

Keyboard and Focus

  • Focusing the input opens the panel; once it is open, Down Arrow moves focus into the first column
  • Each column is one Tab stop: Up Arrow, Down Arrow, Home, End and typed characters select its value
  • Esc closes the panel; focus inside the panel returns to the input

Content Guidelines

  • The time selector includes at least hours and minutes, such as: 11:30, which can be adapted to 12-hour or 24-hour format during localization
  • When 12-hour clock is selected, it needs to be used together with AM/PM

Design Tokens

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$color-timePicker_range_picker_panel_split-bordervar(--semi-color-border)时间选择器菜单分割线颜色
$color-timePicker_range_panel-borderrgba(0, 0, 0, 0.1)时间选择器描边颜色
$width-timePicker_range_panel-border1px时间选择器菜单分割线宽度
$height-timePicker_panel_body252px时间选择器菜单高度
$width-timePicker_panel_list_ampm72px时间选择器菜单中列宽度 - 上午下午
$width-timePicker_panel_list_hour64px时间选择器菜单中列宽度 - 小时
$width-timePicker_panel_list_minute64px时间选择器菜单中列宽度 - 分钟
$width-timePicker_panel_list_second64px时间选择器菜单中列宽度 - 秒
$width-timePicker_range_panel_scrolllist_body-border2px时间范围选择器双排菜单中间分割线宽度
$spacing-timePicker_range_panel_scrolllist_header_body-padding0时间范围选择器菜单header与内容内边距
$radius-timePicker_range_panelvar(--semi-border-radius-medium)时间范围选择器菜单圆角
$radius-timePicker_inputvar(--semi-border-radius-small)时间范围选择器圆角
$shadow-timePicker_range_panelvar(--semi-shadow-elevated)时间范围选择器菜单阴影