Skip to content

Commit f237643

Browse files
authored
Parse string dates in DatePicker (#793)
1 parent c9913c7 commit f237643

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

packages/core/src/components/DatePicker/DatePicker.tsx

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ type Props = {
4040
// minuteInterval?: number;
4141
// timeZoneOffsetInMinutes?: number;
4242
// error?: boolean;
43-
date?: Date;
43+
date?: Date | string;
4444
format?: string;
4545
onDateChange?: (data?: Date) => void;
46-
defaultValue?: Date;
46+
defaultValue?: Date | string;
4747
disabled?: boolean;
4848
mode?: "date" | "time" | "datetime";
4949
type?: "solid" | "underline";
@@ -102,11 +102,13 @@ const DatePicker: React.FC<React.PropsWithChildren<Props>> = ({
102102
maximumDate,
103103
...props
104104
}) => {
105-
const [value, setValue] = React.useState<any>(date || defaultValue);
105+
const [value, setValue] = React.useState<Date | undefined>(
106+
parseDate(date) || parseDate(defaultValue)
107+
);
106108

107109
React.useEffect(() => {
108110
if (defaultValue != null) {
109-
setValue(defaultValue);
111+
setValue(parseDate(defaultValue));
110112
}
111113
}, [defaultValue]);
112114

@@ -177,7 +179,7 @@ const DatePicker: React.FC<React.PropsWithChildren<Props>> = ({
177179
};
178180

179181
React.useEffect(() => {
180-
setValue(date);
182+
setValue(parseDate(date));
181183
}, [date]);
182184

183185
React.useEffect(() => {
@@ -585,7 +587,16 @@ const styles = StyleSheet.create({
585587

586588
function parseDate(date?: string | Date) {
587589
if (typeof date === "string") {
588-
return new Date(date);
590+
const parsed = Date.parse(date);
591+
if (!isNaN(parsed)) {
592+
return new Date(parsed);
593+
}
594+
console.warn(
595+
"Invalid date string:",
596+
`'${date}'.`,
597+
"See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format"
598+
);
599+
return undefined;
589600
}
590601
return date;
591602
}

0 commit comments

Comments
 (0)