2011-04-08 60 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]; 
}