Gab*_*ins 2 date firebase angular google-cloud-firestore
我一直在尝试从存储在Firestore数据库中的日期获取“时间之前”。
我已经尝试了两个可以做到这一点的软件包,但我无法使其与Firestore时间戳一起使用,老实说,我不敢相信获得此软件包的难度如此之大。
获得自身更新的“时间之前”的最简单方法是什么?
我设法从Firestore的时间戳中获取了完整的日期,而不是它的早期版本。
如果您将日期存储在Firestore中作为timestamp文档中的日期(例如,使用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);
});
Run Code Online (Sandbox Code Playgroud)
您还可以按如下方式使用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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1667 次 |
| 最近记录: |