Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a date property in Realm?

Tags:

ios

swift

realm

I have a Realm database with an object "Events" with a property name "occasion" of type string, a property name "venue" of type string and the other one is "date" of type Date(). My question is how do we query the occasions which have a date the same as today (current day). I have tried this code to retrieve the occasions using the date filter and it does work:

let date = Date()
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.dateFormat = "d MMM yyyy"
let stringDate = dateFormatter.string(from: date)        

todayEvent = realm.objects(Events.self).filter("date = '\(stringDate)'").sorted(byKeyPath: "venue", ascending: true)

The date in the Realm database shows a date in this format "17 Jan 2019 at 12:00:00 AM" even when the date was saved in the format of dd/MM/yyyy. I've tried changing the date format but still, it won't work. Or do I need to set a format for the date property when I declare it in the first place? If so how do I do this in a Realm class object? I've tried but it gave an error. I'm stuck here now. Please help

This is how I saved the data to Realm database :

@IBAction func addNewEventButtonPressed(_ sender: UIButton) {



    let newDataEntry = Events()

    newDataEntry.occasion = occasionTextFile.text!


    let dateString =  dateTextField.text!
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    let dateFromString = dateFormatter.date(from: dateString)

    newDataEntry.date = dateFromString!

    do {
        try realm.write {
            realm.add(newDataEntry)
        }
    } catch {
        print("Error saving data \(error)")
    }


}

like image 999
halim Avatar asked Oct 19 '25 11:10

halim


1 Answers

According to Realm docs (emphasis mine):

The comparison operators ==, <=, <, >=, >, !=, and BETWEEN are supported for Int, Int8, Int16, Int32, Int64, Float, Double and Date property types

Thus, the following should work:

let date = Date()
todayEvent = realm.objects(Events.self)
    .filter("date == %@", date)
    .sorted(byKeyPath: "venue") // sorted in ascending order by default
like image 133
Dan Karbayev Avatar answered Oct 21 '25 02:10

Dan Karbayev