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

前端 未结 4 1817
情深已故
情深已故 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:19

    Massimo Camaro had a great answer. I took the liberty of porting it to Swift and modifying it a little to support a different column name.

    Swift 2.0

    func predicateToRetrieveEventsForDate(aDate:NSDate, predicateColumn:String) -> NSPredicate {
        
        // start by retrieving day, weekday, month and year components for the given day
        let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        let todayComponents = gregorian?.components([.Day, .Month, .Year], fromDate: aDate)
        let theDay = todayComponents?.day
        let theMonth = todayComponents?.month
        let theYear = todayComponents?.year
        
        // now build a NSDate object for the input date using these components
        let components = NSDateComponents()
        components.day = theDay!
        components.month = theMonth!
        components.year = theYear!
        let thisDate = gregorian?.dateFromComponents(components)
        
        // build a NSDate object for aDate next day
        let offsetComponents = NSDateComponents()
        offsetComponents.day = 1
        let nextDate = gregorian?.dateByAddingComponents(offsetComponents, toDate: thisDate!, options: NSCalendarOptions(rawValue: 0))
        
        // build the predicate
        let predicate = NSPredicate(format: "\(predicateColumn) >= %@ && \(predicateColumn) < %@", thisDate!, nextDate!)
        
        return predicate
    }
    

提交回复
热议问题