Hello I'm working a real time chat app for my portfolio, I'm having trouble with converting a timestamp I receive from firebase store.
import {serverTimestamp} from 'firebase/firestore';
I looked at this question similar to my problem How do I convert a Firestore date/Timestamp to a JS Date()?, and I tried to use the solutions that were given, and they didn't quite work as intended. I tried using new date to convert the time stamp to a javascript date directly, and it works well for the older messages I made before adding timestamps, but for new messages I try to create I get errors.
this is the timestamp format I receive from firestore.
createdAt: August 2, 2023 at 7:03:09 PM UTC-5
here is my code.
const handleSubmitForm = async (e) =>{
e.preventDefault();
if(message === "") return;
// this is the firebase timestamp I'm trying to convert.
const messageDate = new Date(serverTimestamp);
console.log(messageDate)
//this deconstucts the firebase auth.currentUser array
const {uid, displayName, photoURL} = auth.currentUser;
//this fulfills the promise to add a document to the "messages" collection with the currently logged in users message and profile info.
await addDoc(messagesRef, {
text: message,
createdAt: messageDate,
user: displayName,
userPic: photoURL,
room,
uid,
});
setMessage("")
}
this is the jsx "messages" is just referring to useState that holds the firebase database that I'm mapping through.
{messages.map((message) =>(
<p className='message-timestamp'>-{message.createdAt.toDate().toDateString()}</p>
))}
as I said every time I try to submit a new message I get this error "index.esm2017.js:6342 Uncaught (in promise) RangeError: Invalid time value" and I tried to console log "message date" and it returns "invaild Date. What am I doing wrong? and How can I convert the firebase timestamp to a javaScript object.