You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于日期从存储Timestamp类型的Firestore获取数据?

按日期查询Firestore中Timestamp类型数据的解决方案

你遇到的问题核心是类型不匹配:Firestore中datetime字段存储的是Timestamp类型,而你用SimpleDateFormat把日期格式化成了字符串,用字符串和Timestamp做相等匹配自然查不到结果。

要实现仅按日期查询,正确的做法是查询目标日期当天的时间范围——即当天00:00:00到23:59:59之间的所有Timestamp数据,用范围查询来筛选。

修改后的代码示例

private fun eventChangeListener() {
    val calendar = Calendar.getInstance()
    
    // 计算当天起始时间(00:00:00.000)
    calendar.set(Calendar.HOUR_OF_DAY, 0)
    calendar.set(Calendar.MINUTE, 0)
    calendar.set(Calendar.SECOND, 0)
    calendar.set(Calendar.MILLISECOND, 0)
    val startOfDay = Timestamp(calendar.time)

    // 计算当天结束时间(23:59:59.999)
    calendar.set(Calendar.HOUR_OF_DAY, 23)
    calendar.set(Calendar.MINUTE, 59)
    calendar.set(Calendar.SECOND, 59)
    calendar.set(Calendar.MILLISECOND, 999)
    val endOfDay = Timestamp(calendar.time)

    val db = FirebaseFirestore.getInstance()
    val collection = db.collection("presensi")
    // 用范围查询筛选当天的Timestamp数据
    val query = collection
        .whereGreaterThanOrEqualTo("datetime", startOfDay)
        .whereLessThanOrEqualTo("datetime", endOfDay)

    val option = FirestoreRecyclerOptions.Builder<Dosen>()
        .setQuery(query, Dosen::class.java)
        .build()
    
    dosenAdapter = DosenAdapter(option)

    with(binding){
        tvNoData.visibility = View.GONE
        rvDosen.layoutManager = LinearLayoutManager(activity)
        rvDosen.setHasFixedSize(true)
        rvDosen.adapter = dosenAdapter
    }
}

关键说明

  1. 时间范围计算:通过Calendar将时间调整到当天的起始和结束时刻,再转换为Firestore的Timestamp类型,保证和数据库中存储的字段类型一致。
  2. 范围查询逻辑:whereGreaterThanOrEqualTo匹配当天及之后的起始时间,whereLessThanOrEqualTo匹配当天的结束时间,两者结合就能精准筛选出当天所有的presensi文档。
  3. 扩展场景:如果要查询非当前日期的数据,只需先将Calendar的日期设置为目标日期,再重复上述时间范围计算步骤即可。

内容的提问来源于stack exchange,提问作者I GustiRanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:01:01