Java 如何查询最近7天';来自Firestore Android的数据
我想查询过去7天的云Firestore数据。我使用Firestore的服务器时间戳也以毫秒为单位存储时间Java 如何查询最近7天';来自Firestore Android的数据,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,我想查询过去7天的云Firestore数据。我使用Firestore的服务器时间戳也以毫秒为单位存储时间 CollectionReference IOTransactions = db.collection(userID) .document("userData").collection("StockTransactions"); Query transactionsQuery = IOTransactions.orderBy("timestam
CollectionReference IOTransactions = db.collection(userID)
.document("userData").collection("StockTransactions");
Query transactionsQuery = IOTransactions.orderBy("timestamp",Query.Direction.DESCENDING);
transactionsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("FirestoreDemo", "Listen failed.", e);
return;
}
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
if (doc.get("timestamp") != null)
transactionsList.add(doc.toObject(StockTransaction.class));
Log.d("Firestore", "Added item");
}
if(transactionsList.size() < 1 )
emptyTransactionsPage.setVisibility(View.VISIBLE);
Log.d("Firestore Reading", "Successfully fetched");
adapter.notifyDataSetChanged();
pb.setVisibility(View.INVISIBLE);
}
});
CollectionReference IOTransactions=db.collection(userID)
.文件(“用户数据”)。收集(“股票交易”);
Query transactionquery=IOTransactions.orderBy(“timestamp”,Query.Direction.DESCENDING);
TransactionQuery.addSnapshotListener(新的EventListener(){
@凌驾
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots,@javax.annotation.Nullable FirebaseFirestoreException e){
如果(e!=null){
Log.w(“FirestoreDemo”,“侦听失败”,e);
返回;
}
用于(QueryDocumentSnapshot文档:queryDocumentSnapshots){
if(doc.get(“timestamp”)!=null)
添加(doc.toObject(StockTransaction.class));
日志d(“Firestore”,“添加项”);
}
if(TransactionList.size()<1)
emptyTransactionsPage.setVisibility(View.VISIBLE);
Log.d(“Firestore读取”,“已成功获取”);
adapter.notifyDataSetChanged();
pb.setVisibility(视图不可见);
}
});
如何查询最近7天内创建的数据
我正在使用Firestore的服务器时间戳来存储时间(以毫秒为单位)
因此,如果您以毫秒为单位存储时间戳,那么您就做错了
如何查询最近7天内创建的数据
为了能够根据时间段查询数据库,时间戳属性应该是o类型Date
和notlong。要了解如何实现这一点,请查看我的回答
一旦正确设置了属性,看起来像这样的查询应该可以做到:
IOTransactions.whereLessThan("timestamp", now).whereGreaterThan("timestamp", sevenDayAgo);
其中
now
和sevenDayAgo
是两个Date
对象,表示当前时间和七天前的某个时刻。据我所知,您也可以使用以下查询来获得结果
Query query = mdb.collection("$YOUR_COLLECTION_NAME").orderBy("$YOUR_FIELD")
.whereGreaterThan("$YOUR_FIELD",$Begin_Date_Object)
.endAt($YOUR_DATE_OBJECT);
注意:您需要在endAt字段和
orderBy必须始终位于startAt()或endAt()方法之前
end at搜索orderBy中包含字段end at值的所有文档我想我不能正确判断servertimestamp是日期格式的,但我也在另一个字段中存储为毫秒。谢谢你的回答,这对我的情况很有效。我以前尝试过一些小的差异,所以它不起作用,但效果很好。亚历克斯,你能帮我吗@Alex Mamo你能看看这个吗