It look like what I thought was going to be something simple, has
turned out to be less so and fraught with danger programatically.
I was just thinking though, would it be easier just to covert the
weekday value into seconds (weekday * 60 * 60 * 24) and subtract that
from the current date? This would save you from the issue of year and
month boundaries. Following code is untested (written in Mail):
My apologies; I did do some testing and found that the resultant
date was always correct.
Could you elaborate on what circumstances this might not be correct?
Did you try starting with a starting date of Jan 1, 2009? The
Weekday would be 5, the Day 1.
Rats, no; I tried the dates at the beginning of 2008, 2003, and
The previous Sunday is December 28, 2008.
... although, hmm, yes, that's the result I get(*). Nevertheless...
Passing a Year, Month, Day of (2009, 1, -3) (-3 == 1 - (5 - 1) in
your original computation) is passing an out-of-bounds value with
dateWithComponents:, with who-knows-what effect. It might be well-
defined, it might not be. The result might change between OS
releases. In other words, it seems a bit ambiguous, so best to
just avoid it.
... point taken. I'll update the documentation accordingly.