Skip to content

Commit

Permalink
feat(@formatjs/intl): add new format key for dateTimeRange
Browse files Browse the repository at this point in the history
fix #4792
  • Loading branch information
longlho committed Jan 2, 2025
1 parent 49a6015 commit 91cc5f1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
22 changes: 9 additions & 13 deletions packages/intl/src/dateTime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function getFormatter(
formats: CustomFormats
onError: OnErrorFn
},
type: 'date' | 'time',
type: 'date' | 'time' | 'dateTimeRange',
getDateTimeFormat: Formatters['getDateTimeFormat'],
options: Parameters<IntlFormatters['formatDate']>[1] = {}
): Intl.DateTimeFormat {
Expand Down Expand Up @@ -119,28 +119,24 @@ export function formatDateTimeRange(
config: {
locale: string
timeZone?: string
formats: CustomFormats
onError: OnErrorFn
},
getDateTimeFormat: Formatters['getDateTimeFormat'],
...[from, to, options = {}]: Parameters<IntlFormatters['formatDateTimeRange']>
): string {
const {timeZone, locale, onError} = config
const fromDate = typeof from === 'string' ? new Date(from || 0) : from
const toDate = typeof to === 'string' ? new Date(to || 0) : to

const filteredOptions = filterProps(
options,
DATE_TIME_FORMAT_OPTIONS,
timeZone ? {timeZone} : {}
) as Intl.DateTimeFormatOptions

try {
return getDateTimeFormat(locale, filteredOptions).formatRange(
fromDate,
toDate
)
return getFormatter(
config,
'dateTimeRange',
getDateTimeFormat,
options
).formatRange(fromDate, toDate)
} catch (e) {
onError(
config.onError(
new IntlFormatError('Error formatting date time range.', config.locale, e)
)
}
Expand Down
9 changes: 8 additions & 1 deletion packages/intl/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export interface ResolvedIntlConfig<T = string> {

export interface CustomFormats extends Partial<Formats> {
relative?: Record<string, Intl.RelativeTimeFormatOptions>
dateTimeRange?: Record<string, Intl.DateTimeFormatOptions>
}

export interface CustomFormatConfig<Source = string> {
Expand All @@ -88,6 +89,12 @@ export interface CustomFormatConfig<Source = string> {
: string
}

export type FormatDateTimeRangeOptions = Omit<
Intl.DateTimeFormatOptions,
'localeMatcher'
> &
CustomFormatConfig<'dateTimeRange'>

export type FormatDateOptions = Omit<
Intl.DateTimeFormatOptions,
'localeMatcher'
Expand Down Expand Up @@ -122,7 +129,7 @@ export interface IntlFormatters<TBase = unknown> {
this: void,
from: Parameters<Intl.DateTimeFormat['formatRange']>[0] | string,
to: Parameters<Intl.DateTimeFormat['formatRange']>[1] | string,
opts?: FormatDateOptions
opts?: FormatDateTimeRangeOptions
): string
formatDate(
this: void,
Expand Down

0 comments on commit 91cc5f1

Please sign in to comment.