# Date picker API

> Explore the API of Cimpress UI's date picker component.

Source: https://ui.cimpress.io/components/date-picker/api/

## Import

```tsx
import { DatePicker } from '@cimpress-ui/react';
```

## Value format

Date picker uses the `@internationalized/date` package to represent dates and times. You do not need to install this package separately. All exports from `@internationalized/date` are re-exported from `@cimpress-ui/react/date`.

Refer to [`@internationalized/date` documentation](https://react-spectrum.adobe.com/internationalized/date/index.html) to learn more about it. Remember that whenever the documentation instructs you to import something from `@internationalized/date`, you can import the same thing from `@cimpress-ui/react/date` instead.

### Time

To display a time within the date picker, pass a `CalendarDateTime` instance to the `value` or `defaultValue` prop. You can also control how many date/time segments are displayed using the `granularity` prop.

```tsx
import { DatePicker, Stack, Text } from '@cimpress-ui/react';
import { type CalendarDateTime, parseDateTime } from '@cimpress-ui/react/date';
import { useState } from 'react';

export default function Demo() {
  const [selectedDate, setSelectedDate] = useState<CalendarDateTime | null>(() => parseDateTime('1990-11-01T10:54'));

  return (
    <Stack gap={32}>
      <Text as="p">
        In this example, both fields are controlled with the same state value, but with different display granularity.
      </Text>
      <DatePicker label="Date and time of birth" value={selectedDate} onChange={setSelectedDate} granularity="minute" />
      <DatePicker label="Date of birth" value={selectedDate} onChange={setSelectedDate} granularity="day" />
    </Stack>
  );
}
```

### Time zones

Provide a `ZonedDateTime` instance to the date picker to make it time zone aware.

```tsx
import { DatePicker, Stack, Text } from '@cimpress-ui/react';
import { parseZonedDateTime, toTimeZone, type ZonedDateTime } from '@cimpress-ui/react/date';
import { LocalizationProvider } from '@cimpress-ui/react/i18n';
import { useState } from 'react';

export default function Demo() {
  const [selectedDate, setSelectedDate] = useState<ZonedDateTime | null>(() =>
    parseZonedDateTime('1990-11-01T03:54[Europe/Warsaw]'),
  );

  return (
    <Stack gap={32}>
      <Text as="p">
        In this example, both fields are controlled with the same state value, but with different time zones.
      </Text>
      <LocalizationProvider locale="en-US">
        <DatePicker
          label="Date and time of birth (Warsaw)"
          value={selectedDate}
          onChange={setSelectedDate}
          granularity="minute"
        />
        <DatePicker
          label="Date and time of birth (Los Angeles)"
          value={selectedDate ? toTimeZone(selectedDate, 'America/Los_Angeles') : null}
          onChange={(value) => setSelectedDate(value ? toTimeZone(value, 'Europe/Warsaw') : null)}
          granularity="minute"
        />
      </LocalizationProvider>
    </Stack>
  );
}
```

## Controlled/uncontrolled usage

```tsx
import { DatePicker, Stack } from '@cimpress-ui/react';
import { type CalendarDate, getLocalTimeZone, today } from '@cimpress-ui/react/date';
import { useState } from 'react';

export default function Demo() {
  const [selectedDate, setSelectedDate] = useState<CalendarDate | null>(() => today(getLocalTimeZone()));

  return (
    <Stack gap={32}>
      <DatePicker label="Date of birth (controlled)" value={selectedDate} onChange={setSelectedDate} />
      <DatePicker label="Date of birth (uncontrolled)" defaultValue={today(getLocalTimeZone())} />
    </Stack>
  );
}
```

## Imperative API

```tsx
import { Button, DatePicker, type DatePickerApi, Stack } from '@cimpress-ui/react';
import { getLocalTimeZone, today } from '@cimpress-ui/react/date';
import { useRef } from 'react';

export default function Demo() {
  const apiRef = useRef<DatePickerApi>(null);

  return (
    <Stack gap={16}>
      <DatePicker label="Date of birth" defaultValue={today(getLocalTimeZone())} apiRef={apiRef} />

      <Button onPress={() => apiRef.current?.focus()}>Focus</Button>
    </Stack>
  );
}
```

## Accessibility notes

Grids in the popup calendar follow the [ARIA grid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/grid/#layoutgridsforgroupingwidgets). See the linked page for a list of available keyboard interactions.

Each date and time unit in the date picker field is an individually focusable and editable segment. Each segment can be edited using a keyboard, and incremented/decremented using up/down arrow keys. Use left/right arrow keys or the Tab key to move between segments.

`DatePicker` requires a textual label to remain accessible to assistive technologies. See our [accessibility guide](/dev-guides/accessibility#labelling) for more details.

## Changing the calendar system

By default, `DatePicker` selects a calendar system based on the application's locale. You can force the date picker to use a specific calendar system using a [locale extension subtag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#adding_a_calendar_type_via_the_locale_string).

```tsx
import { DatePicker, Stack } from '@cimpress-ui/react';
import { LocalizationProvider } from '@cimpress-ui/react/i18n';

export default function Demo() {
  return (
    <Stack gap={32}>
      <LocalizationProvider locale="en-US-u-ca-gregory">
        <DatePicker label="Date of birth" description="This date picker uses the Gregorian calendar." />
      </LocalizationProvider>

      <LocalizationProvider locale="en-US-u-ca-indian">
        <DatePicker label="Date of birth" description="This date picker uses the Indian calendar." />
      </LocalizationProvider>
    </Stack>
  );
}
```

## Forms

Date picker can integrate with native HTML forms. See our [forms guide](/dev-guides/forms) to learn how to work with forms.

## API reference

### DatePicker

Allows users to enter or select a date and time value.

See [date picker usage guidelines](https://ui.cimpress.io/components/date-picker/).

- `ref`: `Ref<HTMLDivElement>`

  The `ref` type for this component.

**Props: `DatePickerProps<T extends DateValue>`**

- `id`: `string`

  The element's unique identifier. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id).

- `data-cim-style-root`: `boolean`

  Use this attribute to "claim" the component tree for exclusive Cimpress UI usage.

- `UNSAFE_className`: `string`

  Sets the CSS className for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `UNSAFE_style`: `CSSProperties`

  Sets the CSS style for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `label`: `string`

  The content to display as the label.

- `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.

- `form`: `string`

  The `<form>` element to associate the input with.
  The value of this attribute must be the id of a `<form>` in the same document.
  See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form).

- `name`: `string`

  The name of the input element, used when submitting an HTML form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#name).

- `description`: `string`

  A description for the field. Provides a hint such as specific requirements for what to choose.

- `error`: `FieldError`

  An error message for the field.

- `validate`: `(value: MappedDateValue) => string | true | string[] | undefined`

  A function that returns an error message (or `true`) if a given value is invalid.
  Validation errors are displayed to the user when the form is submitted.
  For real-time validation, use the `error` prop instead.

- `apiRef`: `RefObject<DatePickerApi | null>`

  A React ref that allows access to the imperative API of this component.

- `onFocus`: `(e: FocusEvent<Element>) => void`

  Handler that is called when the element receives focus.

- `onBlur`: `(e: FocusEvent<Element>) => void`

  Handler that is called when the element loses focus.

- `autoFocus`: `boolean`

  Whether the element should receive focus on render.

- `isRequired`: `boolean`

  Whether user input is required on the input before form submission.

- `isInvalid`: `boolean`

  Whether the input value is invalid.

- `isDisabled`: `boolean`

  Whether the input is disabled.

- `isReadOnly`: `boolean`

  Whether the input can be selected but not changed by the user.

- `value`: `T | null`

  The current value (controlled).

- `defaultValue`: `T | null`

  The default value (uncontrolled).

- `onChange`: `(value: MappedDateValue<T> | null) => void`

  Handler that is called when the value changes.

- `autoComplete`: `string`

  Describes the type of autocomplete functionality the input should provide if any. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautocomplete).

- `focusedValue`: `DateValue | null`

  Controls the currently focused date within the calendar.

- `defaultFocusedValue`: `DateValue | null`

  The date that is focused when the calendar first mounts (uncontrolled).

- `minValue`: `DateValue | null`

  The minimum allowed date that a user may select.

- `maxValue`: `DateValue | null`

  The maximum allowed date that a user may select.

- `isDateUnavailable`: `(date: DateValue) => boolean`

  Callback that is called for each date of the calendar. If it returns true, then the date is
  unavailable.

- `placeholderValue`: `T | null`

  A placeholder date that influences the format of the placeholder shown when no value is
  selected. Defaults to today's date at midnight.

- `granularity`: `Granularity`

  Determines the smallest unit that is displayed in the date picker. By default, this is `"day"`
  for dates, and `"minute"` for times.

- `firstDayOfWeek`: `'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'`

  The day that starts the week.

- `isOpen`: `boolean`

  Whether the overlay is open by default (controlled).

- `defaultOpen`: `boolean`

  Whether the overlay is open by default (uncontrolled).

- `onOpenChange`: `(isOpen: boolean) => void`

  Handler that is called when the overlay's open state changes.

**Props: `StyleProps`**

- `margin`: `Responsive<Spacing | "auto">`

  The amount of margin applied to all edges of this component.

- `marginX`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left and right edges of this component. Takes priority over `margin`.

- `marginY`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top and bottom edges of this component. Takes priority over `margin`.

- `marginTop`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top edge of this component. Takes priority over `marginY` and `margin`.

- `marginRight`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the right edge of this component. Takes priority over `marginX` and `margin`.

- `marginBottom`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the bottom edge of this component. Takes priority over `marginY` and `margin`.

- `marginLeft`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left edge of this component. Takes priority over `marginX` and `margin`.
