TimeField
TimeFields allow users to enter and edit time values using a keyboard. Each part of the time is displayed in an individually editable segment.
install | yarn add @react-spectrum/datepicker |
---|---|
version | 3.0.0-alpha.5 |
usage | import {TimeField} from '@react-spectrum/datepicker' |
Example#
<TimeField label="Event time" />
<TimeField label="Event time" />
<TimeField label="Event time" />
Value#
A TimeField
displays a placeholder value by default. An initial, uncontrolled value can be provided to the TimeField
using the defaultValue
prop. Alternatively, a controlled value can be provided using the value
prop.
Time values are provided using objects in the @internationalized/date package. This library handles correct international date and time manipulation across calendars, time zones, and other localization concerns.
TimeField
only supports selecting times, but values with date components are also accepted. By default, TimeField
will emit Time
objects in the onChange
event, but if a CalendarDateTime
or ZonedDateTime
object is passed as the value
or defaultValue
, values of that type will be emitted, changing only the time and preserving the date components.
import {Time} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(new Time(11, 45));
return (
<Flex gap="size-150" wrap>
<TimeField
label="Time (uncontrolled)"
defaultValue={new Time(11, 45)} />
<TimeField
label="Time (controlled)"
value={value}
onChange={setValue} />
</Flex>
);
}
import {Time} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(new Time(11, 45));
return (
<Flex gap="size-150" wrap>
<TimeField
label="Time (uncontrolled)"
defaultValue={new Time(11, 45)} />
<TimeField
label="Time (controlled)"
value={value}
onChange={setValue} />
</Flex>
);
}
import {Time} from '@internationalized/date';
function Example() {
let [value, setValue] =
React.useState(
new Time(11, 45)
);
return (
<Flex
gap="size-150"
wrap
>
<TimeField
label="Time (uncontrolled)"
defaultValue={new Time(
11,
45
)}
/>
<TimeField
label="Time (controlled)"
value={value}
onChange={setValue}
/>
</Flex>
);
}
Time
values may also be parsed from strings using the parseTime
function. This accepts ISO 8601 formatted time strings such as "04:45:23.123"
. The toString
method of a Time
object can also be used to convert a time object to a string.
Time zones#
TimeField
is time zone aware when a ZonedDateTime
object is provided as the value. In this case, the time zone abbreviation is displayed, and time zone concerns such as daylight saving time are taken into account when the value is manipulated.
In most cases, your data will come from and be sent to a server as an ISO 8601 formatted string. @internationalized/date includes functions for parsing strings in multiple formats into ZonedDateTime
objects. Which format you use will depend on what information you need to store.
parseZonedDateTime
– This function parses a date with an explicit time zone and optional UTC offset attached (e.g."2021-11-07T00:45[America/Los_Angeles]"
or"2021-11-07T00:45-07:00[America/Los_Angeles]"
). This format preserves the maximum amount of information. If the exact local time and time zone that a user selected is important, use this format. Storing the time zone and offset that was selected rather than converting to UTC ensures that the local time is correct regardless of daylight saving rule changes (e.g. if a locale abolishes DST). Examples where this applies include calendar events, reminders, and other times that occur in a particular location.parseAbsolute
– This function parses an absolute date and time that occurs at the same instant at all locations on Earth. It can be represented in UTC (e.g."2021-11-07T07:45:00Z"
), or stored with a particular offset (e.g."2021-11-07T07:45:00-07:00"
). A time zone identifier, e.g.America/Los_Angeles
, must be passed, and the result will be converted into that time zone. Absolute times are the best way to represent events that occurred in the past, or future events where an exact time is needed, regardless of time zone.parseAbsoluteToLocal
– This function parses an absolute date and time into the current user's local time zone. It is a shortcut forparseAbsolute
, and accepts the same formats.
import {parseZonedDateTime} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseZonedDateTime('2022-11-07T00:45[America/Los_Angeles]')}
/>
import {parseZonedDateTime} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
import {parseZonedDateTime} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
TimeField
displays times in the time zone included in the ZoneDateTime
object. The above example is always displayed in Pacific Standard Time because the America/Los_Angeles
time zone identifier is provided. @internationalized/date includes functions for converting dates between time zones, or parsing a date directly into a specific time zone or the user's local time zone, as shown below.
import {parseAbsoluteToLocal} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseAbsoluteToLocal('2021-11-07T07:45:00Z')}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseAbsoluteToLocal(
'2021-11-07T07:45:00Z'
)}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<TimeField
label="Event time"
defaultValue={parseAbsoluteToLocal(
'2021-11-07T07:45:00Z'
)}
/>
Granularity#
The granularity
prop allows you to control the smallest unit that is displayed by a TimeField
. By default, times are displayed with "minute"
granularity. More granular time values can be displayed by setting the granularity
prop to "second"
.
<TimeField
label="Event time"
granularity="second"
defaultValue={parseAbsoluteToLocal('2021-04-07T18:45:22Z')} />
<TimeField
label="Event time"
granularity="second"
defaultValue={parseAbsoluteToLocal(
'2021-04-07T18:45:22Z'
)}
/>
<TimeField
label="Event time"
granularity="second"
defaultValue={parseAbsoluteToLocal(
'2021-04-07T18:45:22Z'
)}
/>
Labeling#
A visual label should be provided for the TimeField
using the label
prop. If the TimeField
is required, the isRequired
and necessityIndicator
props can be used to show a required state.
<Flex gap="size-150" wrap>
<TimeField label="Event time" />
<TimeField label="Event time" isRequired necessityIndicator="icon" />
<TimeField label="Event time" isRequired necessityIndicator="label" />
<TimeField label="Event time" necessityIndicator="label" />
</Flex>
<Flex gap="size-150" wrap>
<TimeField label="Event time" />
<TimeField
label="Event time"
isRequired
necessityIndicator="icon"
/>
<TimeField
label="Event time"
isRequired
necessityIndicator="label"
/>
<TimeField
label="Event time"
necessityIndicator="label"
/>
</Flex>
<Flex
gap="size-150"
wrap
>
<TimeField label="Event time" />
<TimeField
label="Event time"
isRequired
necessityIndicator="icon"
/>
<TimeField
label="Event time"
isRequired
necessityIndicator="label"
/>
<TimeField
label="Event time"
necessityIndicator="label"
/>
</Flex>
Accessibility#
If a visible label isn't specified, an aria-label
must be provided to the TimeField
for
accessibility. If the field is labeled by a separate element, an aria-labelledby
prop must be provided using
the id
of the labeling element instead.
Internationalization#
In order to internationalize a TimeField
, a localized string should be passed to the label
or aria-label
prop.
When the necessityIndicator
prop is set to "label"
, a localized string will be provided for "(required)"
or "(optional)"
automatically.
Events#
TimeField
accepts an onChange
prop which is triggered whenever the time is edited by the user. The example below uses onChange
to update a separate element with a formatted version of the date in the user's locale and local time zone. This is done by converting the date to a native JavaScript Date
object to pass to the formatter. The TimeField
allows editing the time components while keeping the date fixed.
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
let formatter = useDateFormatter({ dateStyle: 'long', timeStyle: 'long' });
return (
<>
<TimeField label="Time" value={date} onChange={setDate} />
<p>
Selected date and time:{' '}
{formatter.format(date.toDate(getLocalTimeZone()))}
</p>
</>
);
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
let formatter = useDateFormatter({
dateStyle: 'long',
timeStyle: 'long'
});
return (
<>
<TimeField
label="Time"
value={date}
onChange={setDate}
/>
<p>
Selected date and time:{' '}
{formatter.format(date.toDate(getLocalTimeZone()))}
</p>
</>
);
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';
function Example() {
let [date, setDate] =
React.useState(
parseAbsoluteToLocal(
'2021-04-07T18:45:22Z'
)
);
let formatter =
useDateFormatter({
dateStyle: 'long',
timeStyle: 'long'
});
return (
<>
<TimeField
label="Time"
value={date}
onChange={setDate}
/>
<p>
Selected date and
time:{' '}
{formatter
.format(
date.toDate(
getLocalTimeZone()
)
)}
</p>
</>
);
}
Validation#
TimeField
can display a validation state to communicate to the user whether the current value is valid or invalid. Implement your own validation logic in your app and pass either "valid"
or "invalid"
via the validationState
prop. The errorMessage
prop can be used to communicate errors to the user.
This example validates that the selected time is on a 15 minute increment.
function Example() {
let [time, setTime] = React.useState(new Time(9, 15));
return (
<TimeField
label="Meeting time"
value={time}
onChange={setTime}
validationState={time.minute % 15 ? 'invalid' : 'valid'}
description="Select a meeting time"
errorMessage="Meetings start every 15 minutes." />
);
}
function Example() {
let [time, setTime] = React.useState(new Time(9, 15));
return (
<TimeField
label="Meeting time"
value={time}
onChange={setTime}
validationState={time.minute % 15
? 'invalid'
: 'valid'}
description="Select a meeting time"
errorMessage="Meetings start every 15 minutes."
/>
);
}
function Example() {
let [time, setTime] =
React.useState(
new Time(9, 15)
);
return (
<TimeField
label="Meeting time"
value={time}
onChange={setTime}
validationState={time
.minute % 15
? 'invalid'
: 'valid'}
description="Select a meeting time"
errorMessage="Meetings start every 15 minutes."
/>
);
}
Minimum and maximum values#
The minValue
and maxValue
props can also be used to perform builtin validation. This displays an invalid state if the user enters an invalid time into the time field.
This example only accepts times between 9 AM and 5 PM.
<TimeField
label="Meeting time"
minValue={new Time(9)}
maxValue={new Time(17)}
defaultValue={new Time(8)} />
<TimeField
label="Meeting time"
minValue={new Time(9)}
maxValue={new Time(17)}
defaultValue={new Time(8)} />
<TimeField
label="Meeting time"
minValue={new Time(
9
)}
maxValue={new Time(
17
)}
defaultValue={new Time(
8
)}
/>
Props#
Name | Type | Default | Description |
isQuiet | boolean | false | Whether the time field should be displayed with a quiet style. |
hourCycle | 12 | 24 | — | Whether to display the time in 12 or 24 hour format. By default, this is determined by the user's locale. |
granularity | 'hour'
| 'minute'
| 'second'
| 'millisecond' | 'minute' | Determines the smallest unit that is displayed in the time picker. |
hideTimeZone | boolean | — | Whether to hide the time zone abbreviation. |
placeholderValue | T | — | A placeholder time to display when no value is selected. Defaults to 12:00 or 00:00 depending on the hour cycle. |
minValue | TimeValue | — | The minimum allowed time that a user may select. |
maxValue | TimeValue | — | The maximum allowed time that a user may select. |
isDisabled | boolean | — | Whether the input is disabled. |
isReadOnly | boolean | — | Whether the input can be selected but not changed by the user. |
validationState | ValidationState | — | Whether the input should display its "valid" or "invalid" visual styling. |
isRequired | boolean | — | Whether user input is required on the input before form submission.
Often paired with the |
autoFocus | boolean | — | Whether the element should receive focus on render. |
label | ReactNode | — | The content to display as the label. |
value | T | — | The current value (controlled). |
defaultValue | T | — | The default value (uncontrolled). |
labelPosition | LabelPosition | 'top' | The label's overall position relative to the element it is labeling. |
labelAlign | Alignment | 'start' | The label's horizontal alignment relative to the element it is labeling. |
necessityIndicator | NecessityIndicator | 'icon' | Whether the required state should be shown as an icon or text. |
Events
Name | Type | Default | Description |
onFocus | (
(e: FocusEvent
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent
)) => void | — | Handler that is called when the element loses focus. |
onFocusChange | (
(isFocused: boolean
)) => void | — | Handler that is called when the element's focus status changes. |
onKeyDown | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is released. |
onChange | (
(value: <T>
)) => void | — | Handler that is called when the value changes. |
Layout
Name | Type | Default | Description |
flex | Responsive<string
| number
| boolean> | — | When used in a flex layout, specifies how the element will grow or shrink to fit the space available. See MDN. |
flexGrow | Responsive<number> | — | When used in a flex layout, specifies how the element will grow to fit the space available. See MDN. |
flexShrink | Responsive<number> | — | When used in a flex layout, specifies how the element will shrink to fit the space available. See MDN. |
flexBasis | Responsive<number | string> | — | When used in a flex layout, specifies the initial main size of the element. See MDN. |
alignSelf | Responsive<'auto'
| 'normal'
| 'start'
| 'end'
| 'center'
| 'flex-start'
| 'flex-end'
| 'self-start'
| 'self-end'
| 'stretch'> | — | Overrides the alignItems property of a flex or grid container. See MDN. |
justifySelf | Responsive<'auto'
| 'normal'
| 'start'
| 'end'
| 'flex-start'
| 'flex-end'
| 'self-start'
| 'self-end'
| 'center'
| 'left'
| 'right'
| 'stretch'> | — | Specifies how the element is justified inside a flex or grid container. See MDN. |
order | Responsive<number> | — | The layout order for the element within a flex or grid container. See MDN. |
gridArea | Responsive<string> | — | When used in a grid layout, specifies the named grid area that the element should be placed in within the grid. See MDN. |
gridColumn | Responsive<string> | — | When used in a grid layout, specifies the column the element should be placed in within the grid. See MDN. |
gridRow | Responsive<string> | — | When used in a grid layout, specifies the row the element should be placed in within the grid. See MDN. |
gridColumnStart | Responsive<string> | — | When used in a grid layout, specifies the starting column to span within the grid. See MDN. |
gridColumnEnd | Responsive<string> | — | When used in a grid layout, specifies the ending column to span within the grid. See MDN. |
gridRowStart | Responsive<string> | — | When used in a grid layout, specifies the starting row to span within the grid. See MDN. |
gridRowEnd | Responsive<string> | — | When used in a grid layout, specifies the ending row to span within the grid. See MDN. |
Spacing
Name | Type | Default | Description |
margin | Responsive<DimensionValue> | — | The margin for all four sides of the element. See MDN. |
marginTop | Responsive<DimensionValue> | — | The margin for the top side of the element. See MDN. |
marginBottom | Responsive<DimensionValue> | — | The margin for the bottom side of the element. See MDN. |
marginStart | Responsive<DimensionValue> | — | The margin for the logical start side of the element, depending on layout direction. See MDN. |
marginEnd | Responsive<DimensionValue> | — | The margin for the logical end side of an element, depending on layout direction. See MDN. |
marginX | Responsive<DimensionValue> | — | The margin for both the left and right sides of the element. See MDN. |
marginY | Responsive<DimensionValue> | — | The margin for both the top and bottom sides of the element. See MDN. |
Sizing
Name | Type | Default | Description |
width | Responsive<DimensionValue> | — | The width of the element. See MDN. |
minWidth | Responsive<DimensionValue> | — | The minimum width of the element. See MDN. |
maxWidth | Responsive<DimensionValue> | — | The maximum width of the element. See MDN. |
height | Responsive<DimensionValue> | — | The height of the element. See MDN. |
minHeight | Responsive<DimensionValue> | — | The minimum height of the element. See MDN. |
maxHeight | Responsive<DimensionValue> | — | The maximum height of the element. See MDN. |
Positioning
Name | Type | Default | Description |
position | Responsive<'static'
| 'relative'
| 'absolute'
| 'fixed'
| 'sticky'> | — | Specifies how the element is positioned. See MDN. |
top | Responsive<DimensionValue> | — | The top position for the element. See MDN. |
bottom | Responsive<DimensionValue> | — | The bottom position for the element. See MDN. |
left | Responsive<DimensionValue> | — | The left position for the element. See MDN. Consider using start instead for RTL support. |
right | Responsive<DimensionValue> | — | The right position for the element. See MDN. Consider using start instead for RTL support. |
start | Responsive<DimensionValue> | — | The logical start position for the element, depending on layout direction. See MDN. |
end | Responsive<DimensionValue> | — | The logical end position for the element, depending on layout direction. See MDN. |
zIndex | Responsive<number> | — | The stacking order for the element. See MDN. |
isHidden | Responsive<boolean> | — | Hides the element. |
Accessibility
Name | Type | Default | Description |
id | string | — | The element's unique identifier. See MDN. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Advanced
Name | Type | Default | Description |
UNSAFE_className | string | — | Sets the CSS className for the element. Only use as a last resort. Use style props instead. |
UNSAFE_style | CSSProperties | — | Sets inline style for the element. Only use as a last resort. Use style props instead. |
Visual options#
Quiet#
<TimeField label="Event time" isQuiet />
<TimeField label="Event time" isQuiet />
<TimeField
label="Event time"
isQuiet
/>
Disabled#
<TimeField label="Event time" isDisabled />
<TimeField label="Event time" isDisabled />
<TimeField
label="Event time"
isDisabled
/>
Read only#
The isReadOnly
boolean prop makes the TimeField's value immutable. Unlike isDisabled
, the TimeField remains focusable.
<TimeField label="Event time" value={new Time(11)} isReadOnly />
<TimeField
label="Event time"
value={new Time(11)}
isReadOnly
/>
<TimeField
label="Event time"
value={new Time(11)}
isReadOnly
/>
Label alignment and position#
By default, the label is positioned above the TimeField
. The labelPosition
prop can be used to position the label to the side. The labelAlign
prop can be used to align the label as "start" or "end". For left-to-right (LTR) languages, "start" refers to the left most edge of the TimeField
and "end" refers to the right most edge. For right-to-left (RTL) languages, this is flipped.
<TimeField label="Event time" labelPosition="side" labelAlign="end" />
<TimeField
label="Event time"
labelPosition="side"
labelAlign="end"
/>
<TimeField
label="Event time"
labelPosition="side"
labelAlign="end"
/>
Help text#
Both a description and an error message can be supplied to a TimeField. The description is always visible unless the validationState
is “invalid” and an error message is provided. The error message can be used to help the user fix their input quickly and should be specific to the detected error. All strings should be localized. See the Validation section above for an example.
Placeholder value#
When no value is set, a placeholder value is shown. By default, this is midnight. However, this can be overridden by setting the placeholderValue
prop to a more appropriate placeholder for your specific usecase.
<TimeField label="Appointment time" placeholderValue={new Time(9)} />
<TimeField
label="Appointment time"
placeholderValue={new Time(9)}
/>
<TimeField
label="Appointment time"
placeholderValue={new Time(
9
)}
/>
Hide time zone#
When a ZonedDateTime
object is provided as the value of a TimeField
, the time zone abbreviation is displayed by default. However, if this is displayed elsewhere or implicit based on the usecase, it can be hidden using the hideTimeZone
option.
<TimeField
label="Appointment time"
defaultValue={parseZonedDateTime('2022-11-07T10:45[America/Los_Angeles]')}
hideTimeZone />
<TimeField
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
<TimeField
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
Hour cycle#
By default, TimeField
displays times in either 12 or 24 hour hour format depending on the user's locale. However, this can be overridden using the hourCycle
prop if needed for a specific usecase. This example forces the TimeField
to use 24-hour time, regardless of the locale.
<TimeField
label="Appointment time"
hourCycle={24} />
<TimeField
label="Appointment time"
hourCycle={24} />
<TimeField
label="Appointment time"
hourCycle={24}
/>