R – Getting first and last days of current week

cocoacocoa-touchnscalendarnsdatensdatecomponents

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.

Best Solution

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.

Related Question