如何基于时间戳月份查询Firebase Cloud Firestore数据?
解决Firestore按月份/日期查询Timestamp字段的问题
嗨,我来帮你搞定这个Firestore日期查询的问题~
问题根源
你之前用字符串(比如"12-12-2017")和timestamp字段做比较,但Firestore里通过firebase.firestore.FieldValue.serverTimestamp()存储的是Timestamp类型(本质是Date对象的封装),字符串和Timestamp直接比较不会触发正确的范围筛选,所以查询返回了所有数据。
正确思路:用Date对象做范围查询
要查询特定月份的记录,你需要构造该月份的起始时间(当月1日0点)和结束时间(下月1日0点),然后通过两个where条件做范围匹配——这样就能精准获取该月的所有记录。
具体代码示例(AngularFire场景)
比如要查询2017年11月的消费记录:
// 注意:JavaScript的月份是0-based的,10代表11月 const startOfNovember = new Date(2017, 10, 1); // 2017-11-01 00:00:00 const endOfNovember = new Date(2017, 11, 1); // 2017-12-01 00:00:00 const spendsRef = this.db.collection('spend', ref => ref.where("timestamp", ">=", startOfNovember) .where("timestamp", "<", endOfNovember) ); this.items = spendsRef.valueChanges();
通用工具函数(方便复用)
如果需要频繁查询不同月份,可以封装一个生成月份时间范围的函数:
// 传入年份和实际月份(比如1代表1月),返回起始和结束Date对象 function getMonthDateRange(year: number, month: number) { const start = new Date(year, month - 1, 1); // 转成0-based月份 const end = new Date(year, month, 1); return { start, end }; } // 调用示例:查询2017年12月的记录 const { start, end } = getMonthDateRange(2017, 12); const spendsRef = this.db.collection('spend', ref => ref.where("timestamp", ">=", start) .where("timestamp", "<", end) ); this.items = spendsRef.valueChanges();
额外提醒
- 确保你的
timestamp字段确实是用serverTimestamp()或Date对象存储的,如果之前有存字符串格式的旧数据,需要先把它们转换成Timestamp类型,否则查询还是会失效。 - 如果你要查询特定日期(比如2017-11-30),只需要把起始设为当天0点,结束设为次日0点即可,逻辑和月份查询一致。
内容的提问来源于stack exchange,提问作者Syed Sehu Mujammil A
相关产品推荐
相关产品推荐

