Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter events created for the current date in the Realm swift?

How do I filter events created for the current date in the Realm swift? I tried something like below but this wrong.

let dtSource = datasource.filter("Create == NSDate()").count

Update: Getting the filter creating my date as a string.

http://i.stack.imgur.com/8fLX9.png

http://i.stack.imgur.com/HDR2X.png

like image 851
cwilliamsz Avatar asked Mar 13 '16 00:03

cwilliamsz


1 Answers

A query in the form of Create == NSDate() will check exact date equality, which will compare down to the second. If you want to check if a date is between a given interval, like checking if it's on a specific day, regardless of the time of day, you could do a BETWEEN check:

let dtSource = datasource.filter("Create BETWEEN %@", [firstDate, secondDate]).count

Update:

Here's a full code sample to get all date models for the current day:

import RealmSwift

class Event: Object {
    dynamic var date = NSDate()
}

let todayStart = Calendar.current.startOfDay(for: Date())
let todayEnd: Date = {
  let components = DateComponents(day: 1, second: -1)
  return Calendar.current.date(byAdding: components, to: todayStart)!
}()
events = realm.objects(Event.self).filter("date BETWEEN %@", [todayStart, todayEnd])
like image 159
jpsim Avatar answered Nov 12 '22 07:11

jpsim