Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate - one year ago, dilemma

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)

like image 654
CodeGuy Avatar asked Jan 18 '11 22:01

CodeGuy


2 Answers

You use NSDateComponents like so:

- (NSDate *)logicalOneYearAgo:(NSDate *)from {

    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
    [offsetComponents setYear:-1];

    return [gregorian dateByAddingComponents:offsetComponents toDate:from options:0];

}
like image 167
grahamparks Avatar answered Oct 20 '22 18:10

grahamparks


This is covered in the Date and Time Programming Guide section on Calendrical Calculations, Adding Components to a Date

Specifically, the method of interest is dateByAddingComponents:toDate:options.

Using the Apple example as a basis, to subtract one year from the current date, you would do the following:

NSDate *today = [[NSDate alloc] init];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

/*
  Create a date components to represent the number of years to add to the current date.
  In this case, we add -1 to subtract one year.     
*/

NSDateComponents *addComponents = [[NSDateComponents alloc] init];
addComponents.year = - 1;

return [calendar dateByAddingComponents:addComponents toDate:today options:0];
like image 11
Max MacLeod Avatar answered Oct 20 '22 16:10

Max MacLeod