Manipulate value stored in Firebase document field before applying order by

故事扮演 提交于 2020-05-17 06:08:31

问题


In my Firebase Firestore, I have a large number of documents in a collection, each of which has a field called bookTime, which stores a date in String format. The format is dd MM yyyy HH, so we can't sort it in descending order to get a meaningful list with the latest document on top. The format we need for it to work properly is yyyy MM dd HH. This is my query:

mQuery = mQuery.orderBy("bookTime", Query.Direction.DESCENDING);

What change should I make so I can actually get a list with the document having the newest bookTime on top?


回答1:


What change should I make so I can actually get a list with the document having newest bookTime on top?

First of all, don't use Strings to store dates. It's recommended to use Date objects. The Date is a Firestore supported data type.

For more information on how to store a Date, please see my answer from the following post:

  • ServerTimestamp is always null on Firebase Firestore

Once you store the Date correctly, that query will work perfectly fine.


However, if you insist to store the dates and times as Strings, the option that you have is to store them in a format that can be sorted lexicographical and chronological at the same time.

The ISO 8601 format looks like this:

20200329T184525

That's the current time I'm answering this question.

March 29, 2020 6:45:25 PM UTC


来源:https://stackoverflow.com/questions/60913243/manipulate-value-stored-in-firebase-document-field-before-applying-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!