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

Kotlin中如何获取Firebase查询所需的系统时间戳?

Firestore分页查询获取当前系统时间戳的实现方法

根据你news集合中timestamp字段的存储类型不同,有两种对应实现方案:

方案1:字段为Long类型时间戳

如果你存储的是毫秒级Long数值类型的时间戳,直接调用系统方法获取即可:

// 毫秒级时间戳
long currentTimestamp = System.currentTimeMillis();
// 如果你的字段存的是秒级时间戳,改用下行代码
// long currentTimestamp = System.currentTimeMillis() / 1000;

FirebaseFirestore.getInstance().collection("news")
        .orderBy("timestamp",Query.Direction.DESCENDING)
        .startAfter(currentTimestamp)
        .limit(4)
        .get();

方案2:字段为Firestore官方Timestamp类型

如果你用的是Firestore自带的com.google.firebase.Timestamp类型存储时间,直接调用其静态方法获取当前时间:

Timestamp currentTimestamp = Timestamp.now();

FirebaseFirestore.getInstance().collection("news")
        .orderBy("timestamp",Query.Direction.DESCENDING)
        .startAfter(currentTimestamp)
        .limit(4)
        .get();

注意事项

  • 必须保证传入startAfter的参数类型和集合中timestamp字段的存储类型完全一致,否则会出现查询无结果、排序逻辑错误的问题
  • 如果你是做分页加载下一页的逻辑,不要每次查询都传入当前系统时间戳,需要取上一次查询返回的最后一条数据的timestamp值传入startAfter,才能正确承接上一页的内容加载下一页数据

内容的提问来源于stack exchange,提问作者Kenil Barvaliya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:54:05