Reputation: 603
i realize there is absolutely 0 documentation on how to parse a firebase/firestore timestamp in react.
As it shows here https://firebase.google.com/docs/reference/android/com/google/firebase/Timestamp
Timestamp in firebase is composed of seconds and miliseconds.
var newobj={
uid_to:'K365J32fddel3QTxGG94VksXtQP2',
uid_from:'RqVngIRyiJV2XTogLSONZIqoe5h1',
monto:23,
fecha:new Date(),
user:{
from_name:"fabri"
},
status:'pending'
}
firestore.collection('transacciones').add(newobj);
}
Then in the console is showed as this
And when i do a query it brings this
Object {
"fecha": Timestamp {
"nanoseconds": 960000000,
"seconds": 1526130923,
},
"monto": 23,
"status": "pending",
"uid_from": "RqVngIRyiJV2XTogLSONZIqoe5h1",
"uid_to": "K365J32fddel3QTxGG94VksXtQP2",
"user": Object {
"from_name": "fabri",
},
}
How do i parse it into a simple date, or datetime again?
Upvotes: 11
Views: 13994
Reputation: 1
I faced the same issue and resolved it by the following.
You can convert the date to string dateObj.toString()
or new Date().toString
.
Then when you receive that string back from fireStore simply convert it back to time like this new Date(timeObjReceivedFromFireStore)
.
Upvotes: 0
Reputation: 383
Simply call .toDate()
on the firestore timestamp object to turn it into a JS date object.
So for you it would be something like object.fecha.toDate()
. You can then use that to compare dates or use any other date method. You can also then pass it into moment.
You don't need to necessarily set the time with the serverTimestamp()
method, using new Date()
is fine.
Upvotes: 7
Reputation: 3034
I struggled with this too and since I found no answers on SO or anywhere else, here's the solution that I got through trial and error. For sake of being complete here is how I saved the timestamp field to the articles collection:
saveArticle() {
firebase.firestore().collection('articles').add({
title: this.state.title,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
})
}
Then to display the date you need to call the object's toDate() method, convert that to a JavaScript Date object, then convert that to a date string. So in the render I have the below. Hope this saves someone some time.
<Text>{new Date(this.state.article.createdAt.toDate()).toDateString()}</Text>
Upvotes: 17