如何查询时间戳早于n小时的Firestore数据?
Firestore直接查询早于n小时的数据
问题描述
目前我判断数据是否早于n小时的方法是:从Firestore文档中获取timestamp后执行以下代码:
let timestamp = i.get("timestamp") as! Timestamp let lastUpdatedDate = timestamp.dateValue() let currentDate = Date() let cal = Calendar.current let components = cal.dateComponents([.hour], from: lastUpdatedDate, to: currentDate) let diff = components.hour!
这段代码通常在从Firestore获取文档后,通过forEach循环逐个文档执行。请问能否直接通过timestamp字段查询早于n小时的数据?例如:
ref.collection("References").whereField("timestamp", isLessThanOrEqualTo: n hours)
解决方案
当然可以直接通过Firestore的查询语句过滤出早于n小时的数据,这比客户端逐个计算高效得多——无需拉取所有文档到本地处理,能节省带宽和客户端性能。
具体步骤如下:
- 计算当前时间往前推n小时的
Date对象 - 将该
Date转换为Firestore支持的Timestamp类型 - 用转换后的时间作为查询条件,过滤出符合要求的文档
示例代码:
// 替换n为你需要的小时数,比如24代表24小时前 let n = 24 // 计算n小时前的日期 let nHoursAgo = Calendar.current.date(byAdding: .hour, value: -n, to: Date())! // 转换为Firestore Timestamp let cutoffTimestamp = Timestamp(date: nHoursAgo) // 构造并执行查询 let query = ref.collection("References") .whereField("timestamp", isLessThanOrEqualTo: cutoffTimestamp)
注意事项
- 确保Firestore中文档的
timestamp字段存储的是Timestamp类型,而非字符串或其他格式,否则查询无法正常生效。
内容的提问来源于stack exchange,提问作者Milly Alfaro
相关产品推荐
相关产品推荐

