
以上是我的firestore資料庫。現在我想執行搜索以檢查當前日期是否有任何記錄。下面是我用來搜索是否有任何相關資料的代碼。但這是行不通的......它沒有向我提供任何記錄......有誰知道為什么?
Date TodayDateTime = Calendar.getInstance(TimeZone.getTimeZone(timezoneS)).getTime();
SimpleDateFormat dateTime = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = dateTime.format(TodayDateTime);
CollectionReference doc1 = firebaseFirestore.collection("TransactionRecord");
Query query = doc1.whereEqualTo("userId", user.getStudentID())
.whereEqualTo("timeStamp", "18/5/2022");
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
Toast.makeText(ConfirmPaymentActivity.this, "Error while loading ... ! " error.toString(), Toast.LENGTH_SHORT).show();
Log.d("Problem", error.toString());
return;
}
for (DocumentChange dc : value.getDocumentChanges()) {
if (dc.getType() == DocumentChange.Type.ADDED) {
list = dc.getDocument().toObject(TransactionRecordClass.class);
transactionlist.add(list);
TotalSpented = list.totalPrice;
}
}
if (transactionlist.isEmpty()) {
TotalBudgetAmount.setText("RM " df.format(user.getBudgetControl()));
} else if (TotalSpented >user.getBudgetControl()) {
TotalBudgetAmount.setText("RM " df.format(user.getBudgetControl()-TotalSpented));
TotalBudgetAmount.setTextColor(Color.parseColor("#FF0000"));
} else if (TotalSpented < user.getBudgetControl()){
TotalBudgetAmount.setText("RM " df.format(user.getBudgetControl()-TotalSpented));
TotalBudgetAmount.setTextColor(Color.parseColor("#00FF00"));
}
}
uj5u.com熱心網友回復:
問題出在您發送到資料庫的查詢中:
Query query = doc1.whereEqualTo("userId", user.getStudentID())
.whereEqualTo("timeStamp", "18/5/2022");
此代碼將Timestamp您存盤在資料庫中的日期/與字串值進行比較"18/5/2022"。雖然這個字串值對你來說可能讀起來像一個資料,但它不會對資料庫來說,所以它不回傳任何檔案,因為沒有檔案有一個timeStamp使用字串值呼叫的欄位"18/5/2022"。
如果要過濾日期/時間戳,通常需要在查詢中有兩個條件:要回傳的范圍的開始時間戳和結束時間戳。
因此,如果您想回傳一整天,您需要從一天開始的時間戳開始,并以一天結束時的時間戳結束(或者,在開始的時間戳之前結束第二天)。
所以在代碼中可能是這樣的:
// Create the start date from your literal values (month #4 is May)
Date startAt = new GregorianCalendar(2022, 4, 18).getTime();
// Create the end date by adding one day worth of milliseconds
Date endBefore = new Date(Date.getTime() 24*60*60*1000);
Query query = doc1.whereEqualTo("userId", user.getStudentID())
.whereEqualToOrGreaterThan("timeStamp", startAt);
.whereLessThan("timeStamp", endBefore);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/477066.html
