Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Parse Firestore Timestamp

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

enter image description here

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?

like image 471
fguespe Avatar asked May 12 '18 13:05

fguespe


People also ask

How do I convert firebase timestamp to date in react native?

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) .

How do I convert firestore timestamp to date in react JS?

To convert a Firestore Timestamp into a Javascript date, just call . toDate() on the Timestamp. Save this answer.

How do I compare firestore timestamps?

To check if two Timestamp objects are temporally identical you must use the isEqual property (docs). Comparing with == or === will not check for temporal equality- returning false if comparing different object instances.


1 Answers

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>
like image 60
Steve Carey Avatar answered Sep 21 '22 12:09

Steve Carey