IOS and Objective-C: repeating events every quarter

I need the event to repeat every “quarter” (which I suppose means an approximation of about 3 months). Therefore, I could expect this to move the date (but it is not):

NSDateComponents *component = [[NSDateComponents alloc] init]; // quarter component.quarter = 1; self.todoStartDate = [[NSCalendar currentCalendar] dateByAddingComponents: component toDate:self.todoStartDate options: 0]; 

Is there something wrong with adding a “quarter” to the date? It works great when adding a day or week, but not with a quarter.

+4
source share
2 answers

(I would like to add this as a formatted comment to applefreak's answer, which is pretty good, but SO does not allow markup in comments.)

Apple's documentation for NSCalendar says:

Some calendars represented by this API may display their basic unit concepts per year / month / week / day / ... nomenclature. For example, a calendar consisting of 4 quarters per year instead of 12 months using a unit of the month to represent quarters.

Now that might be much clearer, but I think Apple says regular calendars don't have “quarters” at all; they only have years, months (12 of them) and days. But you can subclass NSCalendar (or create a new instance of NSCalendar ?), So that there are only 4 months in a year, and then call those monthly "quarters", and in the interest of such subclasses, Apple has predefined quarter . This is terribly confusing; I am sure that there is a good story behind Apple WTFery.

Anyway, I agree with applefreak that you should deal with the dates of the year / month / day, one way or another, and not with the help of mythical "quarters". After all, what would it mean to add, say, two quarters by March 31, given that Q3 is shorter than Q1? (And the answer will depend on whether it was a leap year?)

If you really want this “event recurring every year from January 1, April 1, July 1 and October 1,” then you should write it. Don't even bother with “adding three months,” which has the same problems as “adding one quarter.”

By the way, other people here noticed the quarter WTF. For example: I want to get a quarter of the value in the NSDateComponents class

0
source

I ran into the same problem, I don’t know why the quarter is not working, so the workaround is replacing the quarter after month * 3. The following shows how to return three quarters back:

  NSDateComponents *dayComponent = [[NSDateComponents alloc] init]; NSCalendar *theCalendar = [NSCalendar currentCalendar]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"QQQ yyyy"; NSDate *currentDate = [NSDate date]; for (int i = -2; i <= 0; i++) { //dayComponent.quarter = i; dayComponent.month = i*3; NSDate *date = [theCalendar dateByAddingComponents:dayComponent toDate:currentDate options:0]; NSString *dateString = [dateFormatter stringFromDate:date]; NSLog(@"date = %@", dateString); } 

Hope all this helps.

0
source

All Articles