use-date-formatter
Props
| Prop name | Type | Default | Description |
|---|---|---|---|
display | useDateFormatterDisplays | Sets predefined formats | |
locale | string | undefined | The locale for date formatting. Used for `Intl.DateTimeFormat` API. | |
intlFormatOptions | DateTimeFormatOptions | undefined | Options forwarded to Intl.DateTimeFormat API. Use to override and fine tailor the defaults when needed. Intl.DateTimeFormat |
Most cases will benefit from using the provided DateTime component as it also allows for better visual and semantic consistency.
useDateFormatter hook allows for locale aware date formatting, providing you a number of predefined options we use on our websites the most.
Hook returns a formatter function which you can then use to format the dates within your components.
A simplest example would be a component displaying the formatted current date:
import { useDateFormatter } from '@flixbus/honeycomb-react'; const CurrentDate = ({ display, locale }) => { const { formatter } = useDateFormatter({display: display, locale}); return <strong>{formatter.format(new Date())}</strong> } <> Today is: <CurrentDate />, but also <CurrentDate display="day, Mon D" /> as well as <CurrentDate locale="uk" display="Month YYYY" /> </>
Hook uses your application locale by default, pass locale parameter to the hook if you need to customize it.
Another pattern that might be useful is date navigation:
import { Formatter, NavHorizontal, NavItem, useDateFormatter } from '@flixbus/honeycomb-react'; const NavDate = ({ date }) => { const { formatter } = useDateFormatter({display: 'day, Mon D'}); return formatter.format(date) } const today = new Date(); <NavHorizontal aria-label="Shortcuts" extraClasses='test'> <NavItem> <NavDate date={new Date(today).setDate(today.getDate() - 1)} /> </NavItem> <NavItem active> <NavDate date={today} /> </NavItem> <NavItem> <NavDate date={new Date(today).setDate(today.getDate() + 1)} /> </NavItem> </NavHorizontal>
Formatter function enables you with many possibilities in terms of customization and performance optimization.
Here is an example on how you can style the formatted output while extracting the parts of the data with formatToParts method:
import { useDateFormatter } from '@flixbus/honeycomb-react'; const CurrentDate = ({ value }) => { const { formatter } = useDateFormatter({display: 'day, Mon D'}); const formattedValueParts = formatter.formatToParts(value); const month = formattedValueParts.find((part) => part.type === 'month').value; const day = formattedValueParts.find((part) => part.type === 'day').value; const weekday = formattedValueParts.find((part) => part.type === 'weekday').value; return <><strong>{weekday}</strong>, <span style={{ color: 'var(--hcr-danger-dark-color)'}}>{month}</span> <span style={{ color: 'var(--hcr-success-dark-color)'}}>{day}</span></>; } <> Today is: <CurrentDate value={new Date()} /> </>