why_vincent
why_vincent

Reputation: 2262

Saving dates in Firebase Database

Sorting some data based on dates in my Android application. It is stored as follows:

Map<Year, Map<Month, Map<Day, Stuff>>>

Year, month and day are simply containing integers. This cannot be saved to Firebase database since it is a map that has a non-string key. I though about flattening this and turning it into Map. Huge compromise on the data structure since it allows data that the previous one does not(and should not) allow. However, Date isn't either a String. I tried something like this:

String key = String.valueOf(date.getTime());

And then using a data structure:

Map<String, Stuff>

Doesn't work either, it seems to use som illegal characters that the String cannot have in Firebase database. So, how would I go about making this work? Would appreciate help.

Upvotes: 4

Views: 8542

Answers (2)

realdm
realdm

Reputation: 295

I would advise you to create a structure that would look like this:

...
date:{
   day:1,
   month:04,
   year:2016,
   timestamp:12345679979 //in milliseconds
}

This way you can easily index the timestamp int the security rule, do a query by Child and use the filter using start At and endAt methods where you would define the timestamps that define the ranges

Upvotes: 8

Adrian Veliz
Adrian Veliz

Reputation: 114

If you use Date, you can convert it to a string with

String date = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);

With dateObject being the date you're working with and

"dd/MM/yyyy"

being the format for the date. You can find formatting information about this in the oracle Customizing Formats tutorial page

Upvotes: 1

Related Questions