React - display a firestore timestamp

后端 未结 6 2054
醉酒成梦
醉酒成梦 2020-12-18 22:38

I am trying to figure out how to display a firestore timestamp in a react app.

I have a firestore document with a field named createdAt.

I am trying to inc

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 23:22

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

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

    For example, for a document like the following:

    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:

提交回复
热议问题