user5556622
user5556622

Reputation:

How to do core data fetch predicate for NSDate in swift? i want to filter it by months

// fetching data

    var request = NSFetchRequest(entityName: "Users")
    request.returnsObjectsAsFaults = false;
    request.predicate = NSPredicate(format: "name = %@", txtUsername.text!)

    do {
        let results:NSArray = try context.executeFetchRequest(request) as! [NSManagedObject]

        if (results.count > 0){
            var res = results[0] as! NSManagedObject
            txtname.text = res.valueForKey("name") as! String
            txtPassword.text = res.valueForKey("password") as! String

            print(results.count)

have no idea how to predicate NSdate, my entity have three attributes and one of is of date type so if any body knows then do please tell me with an example

Upvotes: 1

Views: 1688

Answers (1)

Ankita Shah
Ankita Shah

Reputation: 2248

You can do something like

Get the first date and last date of a month and then use it like

let startDate = NSDate().startOfMonth()
let endDate = NSDate().endOfMonth()
request.predicate = NSPredicate(format: "dateField >= %@ AND dateField <= %@", startDate!, endDate!)

Where startDate and endDate are NSDate variables. This will get you data for current month. Similarly you can use it for other months too.

You can use below code to get start and end date of month

extension NSDate {

    func startOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let currentDateComponents = calendar.components([.Year, .Month], fromDate: self)
        let startOfMonth = calendar.dateFromComponents(currentDateComponents)

        return startOfMonth
    }

    func dateByAddingMonths(monthsToAdd: Int) -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let months = NSDateComponents()
        months.month = monthsToAdd

        return calendar.dateByAddingComponents(months, toDate: self, options: [])
    }

    func endOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        if let plusOneMonthDate = dateByAddingMonths(1) {
            let plusOneMonthDateComponents = calendar.components([.Year, .Month], fromDate: plusOneMonthDate)

            let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1)

            return endOfMonth
        }

        return nil
    }
}

Upvotes: 3

Related Questions