-1

I have a core data entity.The creation date of each entry is saved as an attribute in the entity.I want to display all entries since last sunday to the current day.How can I perform this?.Should I also add the the day of entry as an attribute???

Vineeth Krishnan
  • 432
  • 2
  • 9
  • 20

2 Answers2

1

this will help you to get the date of the last sunday adjust the value by which day of the week you are on then compare the retrieved dates with this date

extension NSDate {

func dayOfWeek() -> Int? {
    if
        let cal: NSCalendar = NSCalendar.currentCalendar(),
        let comp: NSDateComponents = cal.components(.Weekday, fromDate: self) {
            return comp.weekday
    } else {
        return nil
    }
  }
}

 let calendar = NSCalendar.currentCalendar()
 let lastSundayDate = calendar.dateByAddingUnit(.Day , value: -NSDate().dayOfWeek()!, toDate: NSDate(), options: [])
sherif.Khaled
  • 294
  • 2
  • 8
1

The recommended way to find the last sunday is nextDateAfterDate:components:options: of NSCalendar searching backwards

let components = NSDateComponents()
components.weekday = 1 // 1 = sunday
let lastSunday = NSCalendar.currentCalendar().nextDateAfterDate(NSDate(), matchingComponents: components, options: [.SearchBackwards, .MatchNextTime])

Set the fetch predicate to consider dates after (>) lastSunday

vadian
  • 274,689
  • 30
  • 353
  • 361