Search code examples
androidrealmrealm-mobile-platform

Sort by Date in Realm


I would like to sort informations by date. For example data format is : Nov 10, 2017. I am trying something like this:

RealmResults<ResultFavorite> resultFavoritesReleaseDate = realm.where(ResultFavorite.class).sort("releaseDate", Sort.DESCENDING).findAll();

But it doesn't work. The fieldName in query is a String.


Solution

  • When you say 'it doesn't work', I'm assuming that in actual fact the records are sorted, but in string descending order rather than date order.

    There are two options that I can see.

    Firstly, Date is a supported Realm field type, so you could change your field to be of that type (or an optional: Date? if using Kotlin). Your query as is should then work. This would be the preferred solution.

    The second option is far less elegant, but would be necessary if you are unable to change the field type. In that case you would need to query all objects, and then map the result type to an array, and sort using a java or Kotlin sort routine. The sort criteria would be on a conversion from the String to a Date. This is slow and inefficient in terms of memory usage too.