views:

516

answers:

2

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.

+2  A: 

Use NSDateComponents to get the weekday, which is from 1 for Sunday to 7.

Once you have the weekday number, calculate the difference between it, and your first day of the week. For instance if you consider Monday (2) to be the first day, then how many days earlier was it (or would it be). If the weekday is 4 (Wed) then the difference is 2. This means that if you subtract two days from the original date, you will get the first day of the week that it lies in.

Check the documentation for details, because you will need to deal with the fact that these object also include time attributes. If you can, make sure that the time values are always zero when you are only interested in dates and date comparisons.

Michael Dillon
how can I get a NSDate from it? More precisely, which fields of NSDateComponents I have to fill besides weekday, to get NSCalendar to convert it to first NSDate of week?
Farcaller
Check “Calendars, Date Components, and Calendar Units” at the documentation link in my answer. It's fairly obvious.
Michael Dillon
+1  A: 

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)
Farcaller
Is that using PyObjC? http://pyobjc.sourceforge.net/
Michael Dillon
yes, it's pretty good for solving such problems in quick way. With ipython as shell you can get results fast and without write-compile-run loops over and over.
Farcaller
The NSDateComponents approach will correctly handle days which don't have 60*60*24 seconds.
Matt G