按季度计算日期

时间:2012-04-06 18:31:22

标签: objective-c algorithm date

我正在寻找一种简单而有效的Objective-C算法,该算法从一年中的给定四分之一(3个月)开始,增加或减少特定数量的季度。

例如,在2012年第一季度增加10个季度,我得到年份:2012年+楼层(10/4)= 2012 + 2 = 2014年,然后季度:1 + Mod(10,4)= 1 + 2 = Q3。从2011年第3季度开始减去2个季度,我想在2011年第1季度结束。

最优雅的代码是什么?

2 个答案:

答案 0 :(得分:3)

代码从此处更改:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW1

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
          initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

[offsetComponents setMonth:3]; // one quarter

NSDate *oneQuarterFromToday = [gregorian dateByAddingComponents:offsetComponents
          toDate:today options:0];

答案 1 :(得分:1)

- (void)addQuarters:(NSInteger)quarters toYear:(NSInteger *)currentYear andQuarter:(NSInteger *)currentQuarter {
    if (*currentYear < 0 ||
        *currentQuarter < 1 ||
        *currentQuarter > 4) {
        return;
    }

    *currentYear += quarters / 4;
    *currentQuarter += quarters % 4;

    if (*currentQuarter  > 4) {
        *currentQuarter -= 4;
        *currentYear += 1;
    } else if (*currentQuarter < 1) {
        *currentQuarter += 4;
        *currentYear -= 1;
    }
}

// Example of use:
NSInteger year = 2012;
NSInteger quarter = 2;

[self addQuarters:-7 toYear:&year andQuarter:&quarter];
NSLog(@"Quarter %i of %i", quarter, year);
// Output: Quarter 3 of 2010