Skip to content

Commit

Permalink
refactor: supports previous locales arg
Browse files Browse the repository at this point in the history
  • Loading branch information
huynl-96 committed Sep 22, 2022
1 parent 11af8ba commit 7d182a7
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions packages/shared/useDateFormat/index.ts
Expand Up @@ -29,7 +29,15 @@ const defaultMeridiem = (hours: number, minutes: number, isLowercase?: boolean,
return isLowercase ? m.toLowerCase() : m
}

export const formatDate = (date: Date, formatStr: string, options: UseDateFormatOptions) => {
const isLocaleArgument = (
arg: UseDateFormatOptions | Intl.LocalesArgument,
): arg is Intl.LocalesArgument => typeof arg === 'string' || arg instanceof Intl.Locale || Array.isArray(arg)

export const formatDate = (date: Date, formatStr: string, options: UseDateFormatOptions | Intl.LocalesArgument) => {
// handle deprecated `locales` argument
if (isLocaleArgument(options))
options = { locales: options }

const years = date.getFullYear()
const month = date.getMonth()
const days = date.getDate()
Expand All @@ -44,8 +52,8 @@ export const formatDate = (date: Date, formatStr: string, options: UseDateFormat
YYYY: () => years,
M: () => month + 1,
MM: () => `${month + 1}`.padStart(2, '0'),
MMM: () => date.toLocaleDateString(options.locales, { month: 'short' }),
MMMM: () => date.toLocaleDateString(options.locales, { month: 'long' }),
MMM: () => date.toLocaleDateString((<UseDateFormatOptions>options).locales, { month: 'short' }),
MMMM: () => date.toLocaleDateString((<UseDateFormatOptions>options).locales, { month: 'long' }),
D: () => String(days),
DD: () => `${days}`.padStart(2, '0'),
H: () => String(hours),
Expand All @@ -58,9 +66,9 @@ export const formatDate = (date: Date, formatStr: string, options: UseDateFormat
ss: () => `${seconds}`.padStart(2, '0'),
SSS: () => `${milliseconds}`.padStart(3, '0'),
d: () => day,
dd: () => date.toLocaleDateString(options.locales, { weekday: 'narrow' }),
ddd: () => date.toLocaleDateString(options.locales, { weekday: 'short' }),
dddd: () => date.toLocaleDateString(options.locales, { weekday: 'long' }),
dd: () => date.toLocaleDateString((<UseDateFormatOptions>options).locales, { weekday: 'narrow' }),
ddd: () => date.toLocaleDateString((<UseDateFormatOptions>options).locales, { weekday: 'short' }),
dddd: () => date.toLocaleDateString((<UseDateFormatOptions>options).locales, { weekday: 'long' }),
A: () => meridiem(hours, minutes),
AA: () => meridiem(hours, minutes, false, true),
a: () => meridiem(hours, minutes, true),
Expand Down

0 comments on commit 7d182a7

Please sign in to comment.