2011-04-08 94 views
1

我试图确定每年有24次付款(即每月两次)的付款时间表。付款并不总是第1和第15。我必须从某一天开始,然后计算从那里开始的两次月付。NSCalendar将半个月添加到NSDate中

NSCalendar和NSDateComponents只能够添加整数天,周,月等。我真正需要做的是能够添加0.5个月,但它只能处理整数。我不能只添加15天,因为几个月有不同的天数(这是NSCalendar应该为我们处理的魔法的一部分)。每个月的第一笔付款应该在每月的发言日,所以如果付款在8日开始,那么每笔付款应该在8日,每笔付款应该在8日和半月。这就是并发症进来的地方。我想至少我可以使用每月增加来获得所有的奇数付款。获得这些偶数付款的日期是困难的部分。

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

回答

2

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

NSTimeInterval oneMonthInterval = [oneMonthLater timeIntervalSinceDate:startDate]; 
NSTimeInterval halfMonthInterval = oneMonthInterval/2.0; 
NSDate *halfAMonthLater = [startDate dateByAddingTimeInterval:halfMonthInterval]; 
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]; 
}