0

Is there any way possible to retrieve all users added within the last 7 days? When a user is added, a timestamp incl. date is added to their "information".

Like this for instance: enter image description here

So the date formula is: D/M/YYYY. Can anyone help me understand how to do this?

PS: The weird OL3geebfiGfn..... etc is the users unique ID.

FeReTu
  • 125
  • 2
  • 11

1 Answers1

3

First of all, store the "added" field in milliseconds using ServerValue.TIMESTAMP. You can refer to this question to know more about how to do that easily.

So, now that you've stored the time in milliseconds, your "added" field would contain a Long value. So, you can now perform filtering on your queries to get the data that you need.

Check out this part of the Firebase reference docs for the filtering methods - specially startAt() and endAt().

For example, you want to retrieve the users added in the last 7 days - so 7 days in milliseconds is 86400000. You can simply run a query that is similar to the following to retrieve the users added during the period of "current time in milliseconds" to "current time in milliseconds - 86400000" :-

firebase.database().ref('posts').startAt(current time - 86400000).endAt(current time);
Rohan Stark
  • 2,346
  • 9
  • 16
  • Well, I have added the timestamp you suggested to `added` and it is showing a number. I am trying to get the `currentTime` as you also wrote, but console logging the `currentTime` variable I have made for the firebase TIMESTAMP prints this: `{.sv: "timestamp"}` ?? – FeReTu Sep 23 '17 at 20:01
  • And therefore I cannot compare the `added` value to the currentTime :( – FeReTu Sep 23 '17 at 20:02
  • I understand what you're saying. This happens because `TIMESTAMP` is saved as a map in the database. Check out [this answer](https://stackoverflow.com/a/25750727/7626492). Although its in java, you can still understand and apply the logic to javascript. – Rohan Stark Sep 23 '17 at 20:18
  • I figured it out thanks to you! Thank you very much kind sir! – FeReTu Sep 23 '17 at 20:24
  • Hahah I'm glad I could help! – Rohan Stark Sep 23 '17 at 20:24