Home > Blockchain >  Android get current datetime and search in Firestore
Android get current datetime and search in Firestore

Time:05-18

enter image description here

The above is my firestore database. Now I would like to perform searching to check whether have any records made on the current date. Below is my code that use to search whether have any related data. But it is unworkable... It didn't provide any record back to me... Does anyone know why?

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"));
        }
    }

CodePudding user response:

The problem is in the query you send to the database:

Query query = doc1.whereEqualTo("userId", user.getStudentID())
        .whereEqualTo("timeStamp", "18/5/2022");

This code compares the date/Timestamp that you store in the database with a string value of "18/5/2022". While this string value may read like a data to you, it doesn't to the database, so it returns no documents, since no documents have a field called timeStamp with a string value of "18/5/2022".


If you want to filter on a date/timestamp, you will usually need to have two conditions in the query: the start timestamp and the end timestamp of the range you want to get back.

So if you want to return an entire day, you'll want to start at the timestamp of the start of the day, and end with the timestamp at the end of the day (or alternatively, end just before the timestamp at the start of the next day).

So in code that could be something like:

// 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);
  • Related