Skip to content

Commit

Permalink
Merge pull request #678 from contember/fix/date
Browse files Browse the repository at this point in the history
fix(react-form): date / datetime fields handling
  • Loading branch information
matej21 committed Mar 15, 2024
2 parents 0ddc167 + e75147c commit 648e0c0
Showing 1 changed file with 18 additions and 3 deletions.
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())
}

0 comments on commit 648e0c0

Please sign in to comment.