我将如何从firebase.firestore.Timestamp.now()
时间戳中减去一周?我有不同的带有时间戳的文档,我需要构建一个函数来检查这些文档中是否有任何文档的时间戳早于 7 天。哎呀,也许有一个内置函数来检查日期是否“过期”?提前致谢。
作为定义在这里,
firebase.firestore.Timestamp.now()
相当于
firebase.firestore.Timestamp.fromMillis(Date.now())
要获得一周前的时间戳,您可以使用:
// 1 week in ms = 1000 * 60 * 60 * 24 * 7 = 604800000
const nowTimestamp = firebase.firestore.Timestamp.now();
const weekOldTimestamp = firebase.firestore.Timestamp.fromMillis(nowTimestamp.toMillis() - 604800000);
// or the shorter
const weekOldTimestamp = firebase.firestore.Timestamp.fromMillis(Date.now() - 604800000);
假设您在名为 的集合中有以下文档/photos
:
{
"title": "My Photo",
"desc": "This is the first photo I uploaded here",
"storageRef": "/userData/userid1/uploads/89q24u2q98y23.png",
"thumbnailRef": "/userData/userid1/uploads/89q24u2q98y23.thumbnail.png",
"createdAt": FieldValue.serverTimestamp(),
}
如果要查找一周前的所有照片,可以使用以下相同语句之一:
firebase.firestore().collection("photos")
.where("createdAt", "<", new Date(Date.now() - 604800000))
.get()
或
const weekAgoTimestamp = firebase.firestore.Timestamp.fromMillis(Date.now() - 604800000);
firebase.firestore().collection("photos")
.where("createdAt", "<", weekAgoTimestamp)
.get()
如果您已经拥有该文档的副本,请从这样的查询中获取:
const aPhotoSnapshot = await firebase.firestore()
.doc("photos/somePhotoId")
.get();
并且您想检查它是否超过一周,您可以使用:
const createdAtTimestamp = aPhotoSnapshot.get("createdAt");
const isWeekOld = createdAtTimestamp.toMillis() < Date.now() - 604800000;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句