Skip to content

Commit a91b65e

Browse files
committed
refactor!: formatDate util function
1 parent 6246225 commit a91b65e

File tree

1 file changed

+56
-6
lines changed

1 file changed

+56
-6
lines changed

src/runtime/utils/text.ts

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,62 @@ export const formatPhone = (input: string, separator = '-') => {
110110
return phone
111111
}
112112

113-
export function formatDate(date: number | string | Date, locale = 'en-us') {
114-
return new Date(date).toLocaleDateString(locale, {
115-
year: 'numeric',
116-
month: 'long',
117-
day: 'numeric',
118-
})
113+
/**
114+
* Formats a date or a date-time using the Intl.DateTimeFormat API.
115+
*
116+
* @param date The date to format (number, string, or Date).
117+
* @param config Optional configuration object.
118+
* @param config.type The format to use: 'date' (default) or 'datetime'.
119+
* @param config.locale A string with a BCP 47 language tag (e.g., 'en-US').
120+
* @param config.options Custom formatting options to override the default.
121+
* @param config.defaultString The string to return if the date is invalid.
122+
*/
123+
export function formatDate(
124+
date: number | string | Date,
125+
{
126+
type = 'date',
127+
locale = 'en-US',
128+
options,
129+
defaultString = '-',
130+
}: {
131+
type?: 'date' | 'datetime'
132+
locale?: string
133+
options?: Intl.DateTimeFormatOptions
134+
defaultString?: string
135+
} = {},
136+
) {
137+
// Validation
138+
if (date === null || date === undefined) {
139+
return defaultString
140+
}
141+
const dateObj = new Date(date)
142+
if (Number.isNaN(dateObj.getTime())) {
143+
return defaultString
144+
}
145+
146+
// Format options
147+
const defaultOptions: Record<'date' | 'datetime', Intl.DateTimeFormatOptions> = {
148+
date: {
149+
year: 'numeric',
150+
month: 'long',
151+
day: 'numeric',
152+
},
153+
datetime: {
154+
year: 'numeric',
155+
month: 'short',
156+
day: 'numeric',
157+
hour: 'numeric',
158+
minute: 'numeric',
159+
},
160+
}
161+
const formatOptions = { ...defaultOptions[type], ...options }
162+
163+
try {
164+
return new Intl.DateTimeFormat(locale, formatOptions).format(dateObj)
165+
}
166+
catch {
167+
return defaultString
168+
}
119169
}
120170

121171
export function formatDateTime(date: number | string | Date, locale = 'en-us') {

0 commit comments

Comments
 (0)