如何根据存储的时间戳查询领域数据库以获取每天的相关数据?

时间:2016-10-10 15:33:33

标签: ios swift realm

这就是我的模型的样子

class Run: Object {
  dynamic var duration:Double = 0
  dynamic var elevation:Double = 0.0
  dynamic var distance:Double = 0.0
  dynamic var filePathString:String = ""
  dynamic var exported:Bool = false
  dynamic var timestamp:Date = Date()
  let locations = List<Location>()

}

运行列表显示在tableView中,其中每个标题表示确切的日期(例如10/10/2016)。

是否有可能构建领域查询以获取每天的相关运行?

要明确,我希望实现类似的目标

let isSameDay = Calendar.current.isDate(date1, inSameDayAs: date2) 

使用Realm查询。

1 个答案:

答案 0 :(得分:2)

Realm允许您使用Apple的NSPredicate格式执行查询。在这种特殊情况下,它应该能够使用BETWEEN语法来检查特定时间段内的日期,特别是代表一天开始的时间戳和结束时间。

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)

let components = NSDateComponents()
components.year = 2016
components.month = 10
components.day = 10
components.hour = 0
components.minute = 0
components.second = 0

// Get the start date
let startDate = calendar?.dateFromComponents(components)

// Get the end date
components.day = 11
let endDate = calendar?.dateFromComponents(components)

// Query for the runs between these two dates
let runDates = realm.objects(Run.self).filter("timestamp BETWEEN {%@, %@}", startDate, endDate)

http://nshipster.com/nsdatecomponents/代码被盗enter image description here