0

I'm having difficulty performing queries with date type (timestamp). How would the correct way of querying date fields in the cCoud Firestore be?

    String created_view = editTextDataFilter.getText().toString();
    String time_variable= "";

    try {

        time_variable= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH).format(new SimpleDateFormat(
                "dd/mm/yyyy", Locale.ENGLISH).parse(created_view));

    }catch (ParseException e){}


db.collection("Students")
            .whereGreaterThan("created_at", time_variable)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {

                        for (QueryDocumentSnapshot document : task.getResult()) {

                            alunosList.add(
                                    new Students(
                                            document.getString("name").toUpperCase(),
                                            document.getString("classroom"),
                                            document.getDate("created_at")));


                            recyclerView.setAdapter(adapter);
                        }
                    }
                    else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });


}

Field Timestamp

I expect the output to bring the records with a date greater than the value entered in the "time_variable", but currently it does not find values.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

In order to be able to query a Firestore database based on a timestamp, you need to pass to the CollectionReference's whereGreaterThan(FieldPath fieldPath, Object value) method a Date object. Passing a String (as you currently do), it won't make your query work.

A query that it will work, should look like this:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(created_view);
db.collection("Students")
        .whereGreaterThan("created_at", date)
        .get()
        .addOnCompleteListener(/* ... */);

If you want to add a timestamp programmatically, plese see my answer from the following code:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Sorry for the delay in answering. It worked, thank you. I change only SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); – josé nunes Apr 03 '19 at 12:24