Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react-form): date / datetime fields handling #678

Merged
merged 1 commit into from Mar 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 18 additions & 3 deletions packages/react-form/src/internal/useFormInputHandler.ts
Expand Up @@ -66,7 +66,7 @@ const ColumnTypeHandlerFactories: Record<SchemaKnownColumnType, ColumnTypeHandle
return null
}
const parsed = Date.parse(value)
return isNaN(parsed) ? null : new Date(parsed)
return isNaN(parsed) ? null : (new Date(parsed)).toISOString().split('T')[0]
},
formatValue: (value: string | null) => {
const parsed = value ? Date.parse(value) : null
Expand All @@ -81,12 +81,13 @@ const ColumnTypeHandlerFactories: Record<SchemaKnownColumnType, ColumnTypeHandle
if (value === '') {
return null
}

const parsed = Date.parse(value)
return isNaN(parsed) ? null : new Date(parsed)
return isNaN(parsed) ? null : (new Date(parsed)).toISOString()
},
formatValue: (value: string | null) => {
const parsed = value ? Date.parse(value) : null
return !parsed || isNaN(parsed) ? '' : new Date(parsed).toISOString().substring(0, 16)
return !parsed || isNaN(parsed) ? '' : toLocalDate(new Date(parsed))
},
defaultInputProps: {
type: 'datetime-local',
Expand All @@ -102,3 +103,17 @@ const ColumnTypeHandlerFactories: Record<SchemaKnownColumnType, ColumnTypeHandle
throw new Error('UUID column type is not supported yet')
},
}

const toLocalDate = (date: Date) => {
const pad = (num: number, length: number = 2) => {
const str = num.toString()
return '0'.repeat(Math.max(0, length - str.length)) + str
}

return pad(date.getFullYear(), 4) +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds())
}