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)
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];
}
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With