Search code examples
swiftcore-data

How to fetch Core Data data from a specific date?


I am trying to show the users amount of water drank from a specific date for example from last Monday. The entities are saved with an UUID, Date and with an Int. Is there a way to show all from a last Monday and add them all together? Here is what I tried but it adds them all together. I am trying to make like a history section in my app and get all data for each day of last week. `

    func getDateMonday(){
    
    let currentDate = Date()
    let mondayComponent = DateComponents(weekday: 2)
    let lastMonday = Calendar.current.nextDate(after: currentDate,
                                              matching: mondayComponent,
                                              matchingPolicy: .nextTime,
                                              repeatedTimePolicy: .first,
                                              direction: .backward)!
    
    let predicate = NSPredicate(format: "date >= %@", lastMonday as NSDate)
    
    let waterFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Water")
    waterFetch.predicate = predicate

    do {
    
    let waterF = try viewContext.fetch(waterFetch)
      
            for all in waterF as! [NSManagedObject] {
                
                let tot = all.value(forKey: "amount") as! Int
                monday += tot
                
    }
    print(currentDate)
    print(mondayComponent)
    print(lastMonday)
    } catch {
        
    }
}`

Solution

  • You get the last Monday with the help of Calendar searching backwards for the first occurrence of weekday = 2

    let currentDate = Date()
    let mondayComponent = DateComponents(weekday: 2)
    let lastMonday = Calendar.current.nextDate(after: currentDate,
                                              matching: mondayComponent,
                                              matchingPolicy: .nextTime,
                                              repeatedTimePolicy: .first,
                                              direction: .backward)!
    

    Then create a predicate

    let predicate = NSPredicate(format: date >= %@, lastMonday as NSDate)
    

    and apply this predicate to your fetch request.


    Side note:

    YYYY is wrong. In a standard calendar use always yyyy