I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.
Given a date, say January 17, 2011
, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011
is a Monday, and one year ago, this day fell on January 18, 2010
(a Monday as well). It turns out that January 18, 2010
is 354 days before January 17, 2011
. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010
, which is a Sunday, not a Monday.
So, in Objective-C with NSDate
and NSCalendar
, how could I implement a function such as:
-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}
In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)
The answer turned out to be pretty simple. It turned out from trial and error. Here's the answer.
if the year is a leap year, subtract 365 days.
if the year is not a leap year, subtract 364 days.