fix(frontend): date input is more flexible and accept default html format as a fallback

This commit is contained in:
Ruben Fiszel
2024-08-13 18:45:55 +02:00
parent 41bf933fb7
commit b424c61e95
+22 -5
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte'
import { format, isValid, parse } from 'date-fns'
import { sendUserToast } from '$lib/toast'
export let value: string | undefined = undefined
export let autofocus: boolean | null = false
@@ -12,13 +13,29 @@
const dispatch = createEventDispatcher()
const defaultDateFormat = 'dd-MM-yyyy'
const defaultHtmlDateFormat = 'yyyy-MM-dd'
function computeDate(value: string | undefined) {
if (dateFormat === undefined) {
dateFormat = 'dd-MM-yyyy'
dateFormat = defaultDateFormat
}
if (value) {
const res = format(parse(value, dateFormat, new Date()), 'yyyy-MM-dd')
return res
if (value && value.length > 0) {
try {
let date = parse(value, dateFormat, new Date())
if (date.toString() === 'Invalid Date') {
console.debug('falling back to default html date format')
date = parse(value, defaultHtmlDateFormat, new Date())
}
const res = format(date, defaultHtmlDateFormat)
return res
} catch (error) {
sendUserToast(
`Failed to parse date: ${value} with format ${dateFormat} and ${defaultHtmlDateFormat}`,
true
)
console.error(`Failed to parse date: ${value}`, error)
return undefined
}
} else {
return undefined
}
@@ -27,7 +44,7 @@
function updateValue(newDate: string | undefined) {
if (newDate && isValid(new Date(newDate))) {
if (dateFormat === undefined) {
dateFormat = 'dd-MM-yyyy'
dateFormat = defaultDateFormat
}
try {