Search items by a Date - Query

I have a a Date type of a field in my collection schema. I need to search and query only the items of a specific day in the month that the user chooses (From a date picker in Android) . I’m passing a LocalDate to that function. after user selection. Now my question is, how can I make a query with that LocalDate type, in order to get the right information?

    override fun filterDiariesByDate(localDate: LocalDate): Flow<RequestState<List<Diary>>> {
        return if (user != null) {
            try {
                realm.query<Diary>(
                    "ownerId == $0 AND date == $1",
                    user.identity, ???
                ).asFlow()
                    .map { result -> RequestState.Success(data = result.list) }
            } catch (e: Exception) {
                flow { emit(RequestState.Error(e)) }
            }
        } else {
            flow { emit(RequestState.Error(UserNotAuthenticatedException())) }
        }
    }

That Date type of a filed actually represents a RealmInstant btw, which is normal.

I’ve tried following the official documentation (https://www.mongodb.com/docs/realm/realm-query-language/#date-operators). And I’ve written a query like this:

    override fun filterDieariesByDate(localDate: LocalDate) {
        ...
        realm.query<Diary>("ownerId == $0 AND date < $1",
            user.identity,
            "${localDate.year}-${localDate.month}-${localDate.dayOfMonth}"
        )
        ...
    }

But I’m getting an error: Unsupported comparison between type ‘timestamp’ and type ‘string’.
Can someone please point me in the right direction? Also it would be great to have some more docs about querying a date.

@111757 : Why don’t you consider converting back the local date to RealmInstant and passing it as an argument to the query.

I’ve tried passing a local date, but even though the result was successful, I did receive an empty list. This is my query:

                realm.query<Diary>(
                    "ownerId == $0 AND date < $1",
                    user.identity,
                    RealmInstant.from(zonedDateTime.toLocalDate().toEpochDay(), 0)
                )

Try running the query at Atlas like this to validate if everything is good or not?

where date is RealmInstant.from(zonedDateTime.toLocalDate().toEpochDay(), 0).

I’ve tried, but still an empty response:

I think so there is something wrong with your date altogether.

Have look at my model
Screenshot 2022-12-13 at 11.43.52

Which get saved like this

And you can search like

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.