0

I wish to retrieve only the object of the current date. I have a JSON structure like the following in the firebase database.

Tried this but didn't show anything correctly:

Calendar now = Calendar.getInstance();
    int year = now.get(java.util.Calendar.YEAR);
    int month = now.get(java.util.Calendar.MONTH);
    int day = now.get(java.util.Calendar.DAY_OF_MONTH);

query = mDatabase.orderByKey().orderByChild("date").equalTo(now.toString());

Sample JSON data in Firebase Database

"n4VB8b3Q7SfRrR8ezdaaUaLRHn93"(uid) : {       
"-LcGXirH22zeZvaFuOzA"(timestamp) : {
  "date" : {
    "date" : 12,
    "day" : 2,
    "hours" : 20,
    "minutes" : 4,
    "month" : 2,
    "seconds" : 0,
    "time" : 1552399440382,
    "timezoneOffset" : -360,
    "year" : 119
  },
  "id" : "-LcGXirH22zeZvaFuOzA",
  "name" : "Testing with year",
  "note" : "with year"
},
"-LcGcoUtkFRtP-ugp2kO" : {
  "date" : {
    "date" : 12,
    "day" : 2,
    "hours" : 20,
    "minutes" : 1,
    "month" : 2,
    "seconds" : 0,
    "time" : 1552399260794,
    "timezoneOffset" : -360,
    "year" : 119
  },
  "id" : "-LcGcoUtkFRtP-ugp2kO",
  "name" : "Testing for today",
  "note" : "Testing for today"
}

I expect the output to be events of only the current date.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Please also add a screenshot of it. – Alex Mamo Apr 12 '19 at 14:03
  • You should not use the old `Date` and `Calendar` classes. [They have severe problems](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api). Use the new Java Date and Time API (in the `java.time` package) instead. – MC Emperor Apr 12 '19 at 14:12

1 Answers1

0

Firebase Database queries can only order/filter on a single property. Since you've stored the date in three separate properties, you can only order/filter on one of them.

For example, to get the child nodes from the year 2019, you'd do:

query = mDatabase.orderByKey().orderByChild("date/year").equalTo(119);

You'll note that the above uses "date/year" to order/filter in the nested year property.


If you want to be able to filter by the entire date, you should store that date in a single property, in a format suitable for filtering. The most common format for this is ISO-8601, which would reflect today's date as:

"20190412"

or

"2019-04-12"

Both of these have the advantage that they are lexicographically sortable: ordering dates in this format as strings result in them also being in chronological order.

To get a Java date in ISO-8601 format you use a SimpleDateFormat object:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String nowAsISO = df.format(new Date());

If you store the above value in say date/iso and want to filter on items from today or later, you'd do:

query = mDatabase.orderByKey().orderByChild("date/is").startAt("2019-04-12");
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807