'Using react native date time picker twice gives an error?
I use expo's datetime picker and it works perfectly fine if I click on it only once. If I click on it twice it gives me the following error:
TypeError: value.getTime is not a function. (In 'value.getTime()', 'value.getTime' is undefined)
This error is located at: in RNDateTimePicker (at MyDateTimePicker.js:52)
This is my date time picker:
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Image, Button, StyleSheet, TouchableOpacity } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import Moment from 'moment';
export default function MyDateTimePicker(props) {
console.log("my date time picker props: ", props);
const title = props.title;
const [date, setDate] = useState(new Date());
const [time, setTime] = useState(new Date());
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const [text, setText] = useState(Moment(date).format('DD MMM YYYY HH:mm'));
const onChange = (event, selectedValue) => {
setShow(Platform.OS === 'ios');
if (mode == 'date') {
const currentDate = selectedValue || new Date();
setDate(new Date(currentDate));
setMode('time');
setShow(Platform.OS !== 'ios'); // to show time
} else {
const currentTime = selectedValue || new Date();
setDate(date.setTime(currentTime.getTime()));
setShow(Platform.OS === 'ios'); // to hide back the picker
setMode('date'); // defaulting to date for next open
}
props.updateDate(date);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
console.log("show date picker");
showMode('date');
};
const showTimepicker = () => {
console.log("show time picker");
showMode('time');
};
return(
<View style={styles.viewStyle}>
<TouchableOpacity onPress={showDatepicker}>
<Text style={styles.inputStyle}>{text}</Text>
</TouchableOpacity>
{show && (
<DateTimePicker
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
minimumDate={new Date()}
showTimeSelect
/>
)}
</View>
)
}
And this is how I use it:
<MyDateTimePicker updateDate={(date) => this.handleDate(date)} />
Where
handleDate(date) {
this.setState({date: date});
}
Again, if I click on the date-time picker only once, it all works fine, but if I try to select second date it breaks and I dont see why.
Solution 1:[1]
The problem is here:
setDate(date.setTime(currentTime.getTime()));
setTime returns a number of seconds passed from 01.01.1970 (which is when the world was created from a javascript developers' perspective), but the data picker expects a Date, not a Number, so it attempts to call getTime on a number, which doesn't go well.
I'm not familiar with this particular data picker, but if you're certain it loses the date part when in the 'time' mode try
setDate(new Date(date.getTime()+currentTime.getTime()));
if that moves you too far into the future setDate(currentTime) might be enough (that applies to the 'time' mode only, 'date' part is fine)
Solution 2:[2]
I was completely stumped on this same error for some time using the react-native-datetimepicker library.
The way it worked for me was I manually created the date in the required format and passed it to the date picker. Using moment().toISOString() did not work for me for some reason, although the format is the same as what comes out of the date picker after you change the date or time there.
The code looks roughly like this:
const [customDate, setCustomDate] = useState(null);
useEffect(() => {
const year = new Date().getFullYear();
const month = new Date().getMonth();
const date = new Date().getDate();
const currentTime = new Date(year, month, date, 8, 11, 0);
setCustomDate(currentTime);
}, []);
const selectDate = (event, selectedDate) => {
const date = selectedDate || customDate;
setCustomDate(date);
};
<DateTimePicker mode="date" value={customDate} onChange={selectDate} />
Solution 3:[3]
For class component datetimepicker
class Productdetails extends Component {
constructor(props) {
super();
this.state = {
rentStartDate: new Date(),
startDate: "",
endDate: "",
mode: false,}
this.onChangeStart = this.onChangeStart.bind(this);
}
onChangeStart(event, selectedDate) {
let currentDate = selectedDate || this.state.rentStartDate;
this.setState({ show: Platform.OS === "ios", rentStartDate: currentDate });
let mydate = JSON.stringify(currentDate)
.split("T")[0]
.trim()
.replace('"', "");
this.setState({ startDate: mydate });
}
showMode(currentMode) {
this.setState({
show: true,
mode: currentMode,
});
}
return(<View style={{ flex: 1}}>
<Text style={{ textAlign: "center" }}>Start Date</Text>
<View
style={{
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 5,
height: 40,
borderRadius: 2,
color: "black",
borderColor: "rgba(38, 38, 38,0.8)",
borderWidth: 1,
backgroundColor: "white",
paddingEnd: 5,
}}
>
<Text
style={{
fontSize: 14,
paddingLeft: 5,
backgroundColor: "white",
color: "black",
}}
>
{this.state.startDate}
</Text>
<TouchableHighlight onPress={() => this.showMode("date")}>
<Image
source={require("../images/calender.png")}
style={{ height: 24, width: 24 }}
/>
</TouchableHighlight>
<Overlay
isVisible={this.state.show}
onBackdropPress={() => {
this.setState({ show: false });
}}
>
<DateTimePicker
testID="dateTimePicker"
value={this.state.rentStartDate}
mode={this.state.mode} //The enum of date, datetime and time
placeholder="select date"
format="DD-MM-YYYY"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
timeZoneOffsetInMinutes={undefined}
modalTransparent={false}
animationType={"fade"}
display="default"
onChange={this.onChangeStart}
style={{ width: 320, backgroundColor: "white" }}
/>
</Overlay>
</View>
<View></View>
</View>)
export default React.memo(Productdetails);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nadia Chibrikova |
| Solution 2 | Dmitry Petrov |
| Solution 3 | Sayan Dey |
