I am making an adroid application. I am saving sales data on firebase with current date. I have formatted the System.currentTimeMillis() into SimpleDateFormat. The date is successfully stored on firebase . Now I want to retrieve sales between two dates. I made two demo sales, one on (30-5-2019) and second on (31-5-2019).
For retrieving the sales data I have just put two above mentioned static dates in my Query and ran it . The problem is that it only gives me one sale record between two dates. It should give me 2 sale records.

Below is my source code.

// Firebase Query
Query Qdates = sales_ref.orderByChild("date").startAt("30-5-2019").endAt("31-5-2019");
        Qdates.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ssn : dataSnapshot.getChildren()) {

                     Sale sale = ssn.getValue(Sale.class);
                     String id =sale.getId();
                     Toast.makeText(getActivity(),id,Toast.LENGTH_LONG).show();
                     String customerName = sale.getShippingInfo().getFirstname()+""+sale.getShippingInfo().getLastnme();
                     String countryName = sale.getShippingInfo().getCountry();
                     int itemscount = sale.getList().size();

                     SalesListItem salesListItem = new SalesListItem(id,customerName,countryName,itemscount);
                     alSalesListItem.add(salesListItem);
                     }
                final CustomAdapter customadapter = new CustomAdapter();
                lv.setAdapter(customadapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        }) ;

The output should be 2 sales i-e with following IDs;
Lg6SwzRLbYg4fMDs4H6 (this sales is made on 30-5-2019)
Lg8N1n40zMBVq6V_1hL (this sales is made on 31-5-2019)

But I am getting only one sale that is (this sales is made on 30-5-2019)

Why I am not getting both sales? Please see the attached image.

firebase.PNG

Dani AI

Generated

The behavior you are seeing is typical when dates are stored as strings. Realtime Database orders strings lexicographically, and your endAt("31-5-2019") will exclude values like 31-5-2019 11:00 because they sort after 31-5-2019. Also, string formats without zero-padding do not sort reliably across months and days. The most robust fix is to store a numeric timestamp and query by a millisecond range. Use SimpleDateFormat only for display.

Example approach:

  • Write a dateMillis property as a long (preferably using the server clock to avoid client skew).
  • Compute an inclusive range for the day(s) you want: startOfDay <= dateMillis <= endOfDay.
// When writing
Map<String, Object> sale = new HashMap<>();
sale.put("dateMillis", ServerValue.TIMESTAMP); // resolves to long on the server
sales_ref.push().setValue(sale);

// When querying
Calendar cal = Calendar.getInstance(); // or setTimeZone as needed
cal.set(2019, Calendar.MAY, 30, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0);
long start = cal.getTimeInMillis();
cal.add(Calendar.DATE, 2); // up to end of 31st
long end = cal.getTimeInMillis() - 1;

Query q = sales_ref.orderByChild("dateMillis").startAt(start).endAt(end);

Make sure all records have the same type for the indexed field and add an index for performance:

"rules": { "sales": { ".indexOn": ["dateMillis"] } }

See Filtering data and Server timestamps in the Firebase docs.

Recommended Answers

All 4 Replies

I don't know firebase, but as nobobdy else has answered....

MAYBE there's a time attached to that data, eg
30-5-2019 10am
31-5-2019 11am
and your query is defaulting to midnight, ie 30-5-2019 00:00 to 31-5-2019 00:00
???

If so the fix is to end the date range with a date one day later.

commented: The more I thought about your reply the more likely that's it. +15
commented: Thanks for trying James. Actually there was need to convert the string date in date object, I did so and the problem solved +3

Hai brother can u explain more about this because I also have a implementation by this

Problem solved. Thanks

Can you show me how to solve this question

commented: Look up. " there was need to convert the string date in date object, I did so and the problem solved" -3
commented: why not create a new post instead? +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.