How can I get first and last days of the current week? What I need is some way of filtering a set of objects with NSDate property to leave only ones, that appear on current week, and then filter them by days. Also I need some way to get localized day names.
I've tried to play with NSCalendar, NSDate and NSDateComponents, but it seems that I can't just check calendar's firstWeekday, as there might be weeks with days from previous/next month.
Ok, here it goes, a python snippet that does the job
def daySec(diff):
return 60*60*24*diff
def weekDays(dt=None):
if not dt:
dt = NSDate.date() # use today
cal = NSCalendar.currentCalendar()
dc = cal.components_fromDate_(NSWeekdayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, dt)
normDt = cal.dateFromComponents_(dc) # get the day-rounded date
shift = dc.weekday() - cal.firstWeekday()
firstDt = normDt.dateByAddingTimeInterval_(daySec(-shift))
lastDt = normDt.dateByAddingTimeInterval_(daySec(-shift+7)) # up to next week's first day midnight
return (firstDt, lastDt)