Skip to content
Snippets Groups Projects
Commit d7600bc3 authored by Konrad Mohrfeldt's avatar Konrad Mohrfeldt :koala:
Browse files

feat: extend useFormattedISODate helper function for advanced use cases

* can now be used to represent date, time and datetime strings
* does support nullish-values with proper types
  (and adds a corrosponding default value)
* allows timezone offset to be stripped for use
  in datetime-local input fields
parent b2e8d868
No related branches found
No related tags found
No related merge requests found
......@@ -60,13 +60,54 @@ export function useAsyncFunction<F extends (...args: never[]) => Promise<unknown
return { fn: wrapper, error, isProcessing }
}
export function useFormattedISODate(date: Ref<Date>) {
type UseFormattedISODateOptions = {
representation?: 'date' | 'time' | 'complete' | undefined
stripOffset?: boolean | undefined
}
export function useFormattedISODate(
date: Ref<Date>,
defaultValue?: MaybeRefOrGetter<Date>,
options?: UseFormattedISODateOptions | undefined,
): ComputedRef<string>
export function useFormattedISODate(
date: Ref<Date | null | undefined>,
defaultValue?: MaybeRefOrGetter<Date>,
options?: UseFormattedISODateOptions | undefined,
): ComputedRef<string | undefined>
export function useFormattedISODate(
date: Ref<Date | null | undefined>,
defaultValue?: MaybeRefOrGetter<Date> | undefined,
options?: UseFormattedISODateOptions | undefined,
) {
const offsetPattern = /(Z|\+\d\d:\d\d)$/
function maybeStripOffset(isoDate: string) {
return options?.stripOffset ? isoDate.replace(offsetPattern, '') : isoDate
}
function maybeAddOffset(isoDate: string, currentDate: Date | undefined) {
if (!options?.stripOffset) return isoDate
const match = isoDate.match(offsetPattern)
if (match) return isoDate
const _currentDate = currentDate ?? new Date()
const offset = (formatISO(_currentDate).match(offsetPattern) as RegExpMatchArray)[0]
return isoDate + offset
}
return computed({
get() {
return formatISO(date.value, { representation: 'date' })
return date.value
? maybeStripOffset(
formatISO(date.value, { representation: options?.representation ?? 'complete' }),
)
: null
},
set(dateValue: string) {
date.value = parseISO(dateValue)
set(dateValue: string | null | undefined) {
const _defaultValue = toValue(defaultValue)
const offsetRefDate = date.value ?? _defaultValue
date.value = dateValue
? parseISO(maybeAddOffset(dateValue, offsetRefDate))
: _defaultValue ?? null
},
})
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment