Reputation: 1280
i have this code in swift:
lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2").sorted("end_date", ascending: false)
now i want to filter with start_date NSDate() but this not work:
lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2 OR start_date >= \(NSDate())").sorted("end_date", ascending: false)
any ideas?
Upvotes: 1
Views: 1097
Reputation: 10573
lists = sharedAppCore.getRealm()
.objects(Event)
.filter("status = 1 OR status = 2 OR start_date >= \(NSDate())")
.sorted("end_date", ascending: false)
Strictly speaking, Above code is not the same as your final code.
filter("status = 1 OR status = 2").filter(predicate).sorted("end_date", ascending: false)
^ Because this predicate same as the following:
filter("(status = 1 OR status = 2) AND end_date >= %@", NSDate())
If you create predicate as all OR
, you can just do the following:
filter("status = 1 OR status = 2 OR end_date >= %@", NSDate())
Additionally, if you compare without hours, you should truncate hours from the date first. Then compare with the truncated date.
Like the following:
let now = NSDate()
let calendar = NSCalendar.currentCalendar()
let component = calendar.components([.Year, .Month, .Day], fromDate: now)
let today = calendar.dateFromComponents(component)! // truncated time
Then use truncated date to compare in the predicate.
let now = NSDate()
let calendar = NSCalendar.currentCalendar()
let component = calendar.components([.Year, .Month, .Day], fromDate: now)
let today = calendar.dateFromComponents(component)! // truncated time
let lists = realm
.objects(Event)
.filter("status = 1 OR status = 2 OR end_date >= %@", today)
.sorted("end_date", ascending: false)
Upvotes: 1
Reputation: 1280
solved with this code:
let predicate = NSPredicate(format: "end_date >= %@", NSDate())
lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2").filter(predicate).sorted("end_date", ascending: false)
Upvotes: 0