NSPredicate- For finding events that occur between a certain date range

前端 未结 4 1802
情深已故
情深已故 2021-01-03 10:42

This is a little more complicated then just

NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"startDate >= %@ AND endDate <= %@\", startDay,         


        
4条回答
  •  渐次进展
    2021-01-03 11:06

    While the proposed solution is correct, it is also quite verbose. I have re-implemented it in Swift 3.0:

    import Foundation
    
    extension NSPredicate {
    
        static func filter(key: String, onDayRangeForDate date: Date, calendar: Calendar = Calendar(identifier: .gregorian)) -> NSPredicate {
    
            let dateComponents = calendar.dateComponents([.day, .month, .year], from: date)
    
            let startOfDay = calendar.date(from: dateComponents)!
    
            let offsetComponents = NSDateComponents()
            offsetComponents.day = 1
            let endOfDay = calendar.date(byAdding: offsetComponents as DateComponents, to: startOfDay)!
    
            return NSPredicate(format: "\(key) >= %@ && \(key) < %@",
                startOfDay as NSDate, endOfDay as NSDate)
        }
    }
    

提交回复
热议问题