React - display a firestore timestamp

When you get timestamps from Firestore they are of the following type:

enter image description here

To convert this into a normal timestamp you can use the .toDate() function.

For example, for a document like the following:

enter image description here

We can use something like:

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  console.log(doc.data().[FIELD].toDate());
});

and the output will be like:

2019-12-16T16:27:33.031Z

Now to process that timestamp further, you can convert it into a string and use regex to modify it according to your needs.

For example: (I'm using Node.js here)

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  var stringified = doc.data().[FIELD].toDate().toISOString();
  //console.log(stringified);
  var split1 = stringified.split('T');
  var date = split1[0].replace(/\-/g, ' ');
  console.log(date);
  var time = split1[1].split('.');
  console.log(time[0]);
});

Will give you an output like this:

enter image description here


After some discussion, we found that the time stamps in OPs user object could be renders as such:

render() { 
const { users, loading } = this.state; 

return ( 
    <div> 
        {loading && <div>Loading ...</div>} 

        {users.map(user => ( 

            <Paragraph key={user.uid}> 

                <key={user.uid}> 
                    {user.email} 
                    {user.name} 
                    {new Date(user.createdAt.seconds * 1000).toLocaleDateString("en-US")}

I recreated your example in a dummy React project, and received the same error as expected.

Error: Objects are not valid as a React child

I was able to get this to render correctly with the following method, which should also work for you:

{new Date(user.createdAt._seconds * 1000).toLocaleDateString("en-US")}

Which, for my sample timestamp, rendered as:

12/30/2019


Be sure you are using a timestamp that was saved to Firestore as:

createdAt: this.props.firebase.Timestamp.fromDate(new Date())

Note: This is assuming that your instance of firebase.firestore() is at this.props.firebase. In other examples you use this.props.firebase, but those methods look like helper methods that you have created yourself.

When this value is fetched, it will be an object with two properties -- _seconds and _nanoseconds.

Be sure to include the underscore. If you use createdAt.seconds it won't work, it must be createdAt._seconds.


Other things I tried:

user.createdAt.toDate() throws toDate() is not a function.

user.createdAt throws Error: Objects are not valid as a React child

new Date(user.createdAt._nanoseconds) renders the wrong date