'Convert String to Date then to timestamp to add to firestore
Okay so I've got two react native componenet DateTimePicker that I use to collect a date and time from the user using the following on change func
const onChangeDate = (event, selectedDate) => {
const currentDate = selectedDate || date;
setDateShow(Platform.OS === 'ios');
setDate(currentDate);
let tempDate = new Date(currentDate);
let date = tempDate.getFullYear() + '-' + tempDate.getMonth() + '-' + tempDate.getDate();
console.log(date); //2022-4-18
setFinalDate(date);
}
const onChangeTime = (event, selectedTime) => {
const currentTime = selectedTime || time;
setTimeShow(Platform.OS === 'ios');
setTime(currentTime);
let tempDate = new Date(currentTime);
let time = tempDate.getHours() + ':' + tempDate.getMinutes() + ':' + tempDate.getSeconds() + tempDate.getMilliseconds();
console.log(time); //0:10:00
setFinalTime(time);
}
After setting a state for finalTime and finalDate
const eventTimestamp = (`${finalDate} ${finalTime}`);
console.log(eventTimestamp) // output is 2022-4-18 0:10:00
I cant seem to convert this into a date() object and then into a timestamp using toMillis() method becuse I want to add this into firestore as a timestamp. Converting it into a date using new Date() gives me Date { NaN } and using firestore method firebase.firestore.Timestamp.fromDate(works) gives me Object { "nanoseconds": NaN, "seconds": NaN, }
Any luck on where I'm going wrong?
Solution 1:[1]
You should parse the date string then convert it into a date()
object. See sample code below:
// Initiate a new Date object.
const eventTimestamp = new Date(
// Parse the string into a date
Date.parse(
`${finalDate} ${finalTime}`
)
)
await setDoc(doc(db, "<collection>", "<document-id>"), {
timestamp: eventTimestamp
});
For more information, you may checkout this documentation.
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 |