I'm using react and typescript, and for datepicker I'm using react-dates.
I want to convert the date to unix when I select it, but I get a ts error.
I get a ts error with a startDate of new Date(startDate).getTime() / 1000.
error
Type 'null' is not assignable to type 'string | number | Date'.
Overload 2 of 4, '(value: string | number): Date', gave the following error.
Argument of type 'Moment | null' is not assignable to parameter of type 'string |
number'. Type 'null' is not assignable to type 'string | number'.ts(2769)
import { DayPickerRangeController } from "react-dates";
import React, { useState } from "react";
import moment from "moment";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
export default function App() {
const [startDate, setStartDate] = useState<moment.Moment | null>(null);
const [endDate, setEndDate] = useState<moment.Moment | null>(null);
const [focusedInput, setFocusedInput] = useState<"startDate" | "endDate">(
"startDate"
);
console.log(new Date(startDate).getTime() / 1000);
return (
<DayPickerRangeController
startDate={startDate}
endDate={endDate}
focusedInput={focusedInput}
numberOfMonths={2}
onFocusChange={(focusedInput) => {
console.log(focusedInput, "focusedInput");
}}
onDatesChange={(selectedDates) => {
if (focusedInput === "startDate") {
console.log(selectedDates, "startDate");
setStartDate(selectedDates.startDate);
} else {
setEndDate(selectedDates.endDate);
}
}}
/>
);
}
CodePudding user response:
The error is correct, as you can’t create a new date from a null value. Instead, make the conversion onDatesChange, so that you know you’ll have a date at that point:
onDatesChange={(selectedDates) => {
if (focusedInput === "startDate") {
console.log(selectedDates, "startDate");
console.log(new Date(selectedDates.startDate).getTime() / 1000);
setStartDate(selectedDates.startDate);
} else {
setEndDate(selectedDates.endDate);
}
}}
Once you can confirm that’s the shape you want it to be, you can create a function convertDateToUnix
handling that conversion, so you can reuse it for both start and end dates