1

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

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

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

4

2 回答 2

2

好吧,如果您可以计算距开始日期 1 个月的日期,则计算半个月仅相差一个除法:

NSTimeInterval oneMonthInterval = [oneMonthLater timeIntervalSinceDate:startDate];
NSTimeInterval halfMonthInterval = oneMonthInterval / 2.0;
NSDate *halfAMonthLater = [startDate dateByAddingTimeInterval:halfMonthInterval];
于 2011-04-08T20:52:37.660 回答
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];
}
于 2011-04-09T03:52:29.090 回答