How can I filter by specific date from realm object in swift?

alphonse :

I have a realm object with date property type of Date , and want to get list of items with specific date.

If I click specific date from calendar, for example 2020-03-06 , then it will present list of items which was created in 2020-03-06.

enter image description here

Jay :

Filtering by date is fully supported on date objects. Here's two quick examples. One for filtering for a specific date (for your question) and one for a date range using BETWEEN.

Note, I have a function makeDate that casts a string to a date object. This example uses a Realm DogClass object that has a dog_birthdate Date property.


This filters for objects with a specific date

let searchDate = self.makeDate(fromString: "06/01/2019")
let specificDateResults = realm.objects(DogClass.self)
                               .filter("dog_birthdate == %@", searchDate)
for dog in specificDateResults {
    print(dog.dog_name)
}

This filters for objects within a date range

let startDate = self.makeDate(fromString: "06/01/2019")
let endDate = self.makeDate(fromString: "06/20/2019")
let dateRangeResuls = realm.objects(DogClass.self)
                           .filter("dog_birthdate BETWEEN {%@,%@}", startDate, endDate)
for dog in dateRangeResuls {
    print(dog.dog_name)
}

EDIT: Using the code in the comment from the OP for testing

let stringDate = "2019-06-01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let searchDate:Date = dateFormatter.date(from: stringDate)!
let result = realm.objects(DogClass.self).filter("dog_birthdate == %@", searchDate)
for dog in result {
    print(dog.dog_name)
}

which works perfectly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33379&siteId=1