diff --git a/src/components/answer/DateTimeAnswer.jsx b/src/components/answer/DateTimeAnswer.jsx index 2b569494..e9913d40 100644 --- a/src/components/answer/DateTimeAnswer.jsx +++ b/src/components/answer/DateTimeAnswer.jsx @@ -4,19 +4,13 @@ import { FormGroup, Form } from "react-bootstrap"; import PropTypes from "prop-types"; import { format, parse } from "date-fns"; import FormUtils from "../../util/FormUtils"; -import Constants from "../../constants/Constants"; import { ConfigurationContext } from "../../contexts/ConfigurationContext"; import classNames from "classnames"; const DateTimeAnswer = (props) => { const { componentsOptions } = useContext(ConfigurationContext); const [date, setDate] = useState(null); - - useEffect(() => { - if (props.value) { - setDate(new Date(parse(props.value, datePickerFormat, new Date()))); - } - }, []); + const [errorMessage, setErrorMessage] = useState(""); const dateFormat = FormUtils.resolveDateTimeFormat( props.question, @@ -26,23 +20,39 @@ const DateTimeAnswer = (props) => { const isDate = FormUtils.isDate(props.question); const isTime = FormUtils.isTime(props.question); + const isTimestampFormat = FormUtils.isTimestamp(props.question); - // DatePicker does not know dateFormat "x", translate to datetime - const datePickerFormat = - dateFormat === "x" - ? componentsOptions.dateTimeAnswer.dateTimeFormat - : dateFormat; - - const handleDateChange = (date) => { - setDate(date); - if (!date) { - props.onChange(""); - } - if (dateFormat === Constants.DATETIME_NUMBER_FORMAT) { - props.onChange(Number(date)); + useEffect(() => { + const parsedDate = parseDate(props.value); + if (parsedDate) { + setDate(parsedDate); } else { - props.onChange(format(date, dateFormat)); + setDate(null); + setErrorMessage( + `Invalid date value ${props.value} of question ${props.question["@id"]}.` + ); + console.error(errorMessage); } + }, [props.value, dateFormat]); + + const parseDate = (value) => { + if (!value) return null; + + const parsed = isTimestampFormat + ? new Date(value) + : parse(value, dateFormat, new Date()); + return isNaN(parsed.getTime()) ? null : parsed; + }; + + const handleDateChange = (selectedDate) => { + setDate(selectedDate); + const timeValue = selectedDate + ? isTimestampFormat + ? selectedDate.getTime() + : format(selectedDate, dateFormat) + : ""; + + props.onChange(timeValue); }; return ( @@ -50,14 +60,14 @@ const DateTimeAnswer = (props) => { {props.label}