NSCalendar为NSDate增加了半个月的时间

时间:2011-04-08 20:12:56

标签: objective-c nsdate nscalendar nsdatecomponents

我正在尝试确定每年有24笔付款(即每月两次)的付款时间表。付款不会总是第1和第15。我必须从某一天开始,然后从那里开始计算每月两次的付款。

NSCalendar和NSDateComponents只能添加整数天,周,月等。我真正需要做的是能够添加0.5个月,但它只处理整数。我不能只添加15天,因为几个月有不同的天数(这是NSCalendar应该为我们处理的魔法的一部分)。本月的第一笔付款应该是每月的说明日,所以如果付款从8日开始,则每笔奇数付款应该是8日,每笔付款都应该是8日半月。这就是复杂性的来源。我至少可以说我可以使用月份来获得所有奇数编号的付款。获取那些偶数付款的日期是困难的部分。

有没有办法通过我缺少的NSCalendar添加半个月?如果没有,你有一个优雅的解决方案,每年产生这24个日期吗?

2 个答案:

答案 0 :(得分:2)

好吧,如果你可以计算一个从开始日期起1个月的日期,计算半个月就只有一个师了:

NSTimeInterval oneMonthInterval = [oneMonthLater timeIntervalSinceDate:startDate];
NSTimeInterval halfMonthInterval = oneMonthInterval / 2.0;
NSDate *halfAMonthLater = [startDate dateByAddingTimeInterval:halfMonthInterval];

答案 1 :(得分:2)

不,你必须自己创建半月计算。为了好玩,我为你写了以下内容。 享受。

- (NSArray *)createPaymentScheduleWithStartDate:(NSDate *)startDate numberOfPayments:(NSUInteger)payments {
    NSUInteger count = 0;
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSMutableArray *schedule = [NSMutableArray arrayWithCapacity:payments];

    // break down the start date for our future payments
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit 
            | NSTimeZoneCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *comps = [cal components:unitFlags fromDate:startDate];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSInteger year = [comps year];


    // For simplicity sake, adjust day larger than 28
    // this way we don't have to test each time we create a date
    // if it valid.
    if (day > 28)
        day = 28;

    // NSDate *a = startDate;
    // because we want all payments to have the same time
    // create the first again
    NSDate *a = [cal dateFromComponents:comps];

    do {
        month++;
        if (month > 12) {
            year++;
            month = 1;
        }

        // create the next month payment date
        comps.month = month;
        comps.day = day;
        comps.year = year;
        NSDate *b = [cal dateFromComponents:comps];

        // find the middle date
        NSTimeInterval m = [b timeIntervalSinceDate:a];
        NSDate *c = [a dateByAddingTimeInterval:m / 2];

        // add dates to our schedule array
        [schedule addObject:a];
        [schedule addObject:c];
        count += 2;

        // adjust to next group of payments
        a = b;

    } while (count < (payments + 5));



    // because we add two payments at a time,
    // we have to adjust that extra payment
    if ([schedule count] > payments) {
        // create range of our excess payments
        NSRange range = NSMakeRange(payments, [schedule count] - payments);
        [schedule removeObjectsInRange:range];
    }

    NSLog(@"Schedule: %@", schedule);
    return [NSArray arrayWithArray:schedule];
}