NSDate - a year ago, a dilemma

I'm trying to do something that is a little difficult for me. But I'm sure someone has an understanding.

Given the date, let's say January 17, 2011I'm trying to figure out the day corresponding to that date a year ago. So, it January 17, 2011’s Monday, and a year ago this day fell on January 18, 2010(Monday too). It turns out that January 18, 2010is 354 days before January 17, 2011. Initially, I thought just to subtract 365 days for a non-leap year and 366 days for a leap year, but if you do this in this case, you will get January 17, 2010it Sunday, not Monday.

So, in Objective-C with NSDateand NSCalendar, how could I implement a function like:

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

In other words, the nth “working day” in the nth month (where “weekday” is Monday or Tuesday or Wednesday, etc.)

+5
source share
5 answers

The answer was pretty simple. It turned out from trial and error. Here is the answer.

if the year is a leap year, subtract 365 days.

if the year is not a leap year, subtract 364 days.

-8
source

You are using NSDateComponents as follows:

- (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];

}
+22
source

, dateByAddingComponents: toDate: options.

Apple , , :

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];
+11

, , , NSCalendar NSDateComponents. NSDate [yourCalendar components:yourComponents fromDate:yourDate], , [yourCalendar dateFromComponents:yourComp].

, , , , .

+3

Substract 1 . 1 , , .

" " 1 , , 29- , 2 .

, 52 + 1 (+2 ).

So, if you apply this logic indefinitely, you will end, years after several years, from June 16 to May 24.

If you do not want this to happen, you need to remember the control year somewhere and base your arithmetic on it.

For example, if the “new” Monday expires 4 days ago (because 3 years have passed), you may prefer to choose Monday time 3 days in advance, so as not to endlessly endure days, years after years.

Hope this helps.

0
source

All Articles