DateTime: React
Allows you to display a date in a consistent way through the use of formats.
Installation
Before you can start using the @chameleon/react component, you’ll need to install it, for more information check: Getting started for developers.
With that done, you’re now ready to implement the component in your application.
import { DateTime } from '@chameleon/react';
export default function Example() {
return <DateTime date={new Date().toISOString()} />;
}
Properties
| Property | Type | Default | Required | Description |
|---|---|---|---|---|
className | String | - | No | Allows extending the class names of the DateTime component. |
date | String | - | No | The timestamp string (ISO8601) of the date to be displayed. |
format | String | dateTimeDefaultFormat | No | The date and time formatting setting. |
locale | { code: String; formatDistance: FormatDistanceFn; formatRelative: FormatRelativeFn; localize: Localize; formatLong: FormatLong; match: Match; options?: LocaleOptions } | Context locale (from ChameleonProvider) | No | Locale to be used for formatting. |
timeZone | String | - | No | Timezone to be used for formatting. |
format
The format prop is used to specify the date and time formatting for the display. You can refer to the date-fns documentation for a list of all available formatting settings.
Some examples of formats are:
dd/MM/yyyy: 13/01/2023dd/MM/yyyy HH:mm: 13/01/2023 14:30HH:mm: 14:30dd MMMM yyyy: 13 January 2023
The values depend on the locale that is set.
Relative time format
In addition to the standard date-fns formats, you can enhance the standard date-fns formats by utilizing the relative value for the format prop.
This value internally leverages the formatDistanceToNow function provided by date-fns. With this approach, you can display relative time using phrases like '2 hours ago.'
For more details on the formatDistanceToNow function, refer to the date-fns documentation.
locale
The DateTime component automatically uses the locale from the ChameleonProvider context. Each brand has a default locale configured in its theme.
If your brand needs to use another locale, you can override it via the locale prop:
import { pt } from '@chameleon/react/locale';
// Override the locale for this component
<DateTime locale={pt} date={new Date().toISOString()} />;
format
The format prop defaults to the theme's configured date format (from themeConfig.dateTime.defaultFormat). You can override it with any date-fns format string.
To access date/time formats from the theme configuration in your own components, use the useThemeConfig hook:
import { useThemeConfig } from '@chameleon/react';
function MyComponent() {
const themeConfig = useThemeConfig();
const { dateFormat, timeFormat, dateTimeFormat } =
themeConfig?.dateTime ?? {};
}