如何从Firestore时间戳(Firebase)获取“多久以前”的时间?

4

我一直在尝试从存储在Firestore数据库中的日期获取“时间前”的信息。

我尝试了两个可以实现此功能的包,但是我无法将其与Firestore时间戳配合使用,而且老实说,我无法相信这件事情会如此困难。

有什么最简单的方法可以自动更新“时间前”吗?

我设法仅从Firestore时间戳中获取完整日期,但无法获取其“时间前”版本。


4
使用 moment.js:moment(firestoreTimestamp.toDate()).fromNow() - ego
1个回答

6
如果您将日期以 timestamp 的形式存储在Firestore文档中(例如使用 FieldValue.serverTimestamp()),则以下JavaScript代码将为您提供自 storedTimestamp 日期以来的经过时间(以毫秒为单位):
    var db = firebase.firestore();

    var docRef = db.collection('yourCollection').doc('yourDocId');

    docRef.get().then(function (doc) {
        if (doc.exists) {
            var storedDate = new Date(doc.data().storedTimestamp);
            var nowDate = new Date();
            var elapsedTime = (nowDate.getTime() - storedDate.getTime());
            console.log(elapsedTime);

        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function (error) {
        console.log("Error getting document:", error);
    });

你也可以使用moment.js库,例如下面的代码可以获取两个日期之间的天数差。

    docRef.get().then(function (doc) {
        if (doc.exists) {
            var storedDate = moment(doc.data().storedTimestamp);
            var nowDate = moment();
            //get the difference in days, for example
            console.log(nowDate.diff(storedDate, 'days'))

        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function (error) {
        console.log("Error getting document:", error);
    });

1
new Date(doc.data().storedTimestamp) 对我没用。new Date(doc.data().storedTimestamp.toDate()) 运行良好。 - LacOniC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接