-1

次のコードを使用して、生年月日の配列から残りの日数を取得したい

for(int i =0;i<_convertedBdates.count;i++){

    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"dd/MM/YYYY"];
    NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];


    NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
    NSDate *secondDate = [tempFormatter dateFromString:curYear];
    NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
    NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
    NSTimeInterval dateDiff = lastDiff  - todaysDiff;
    int day = dateDiff/(3600*24);

    NSLog(@" _newlymadeArray %@",[_convertedBdates objectAtIndex:i]);

    NSLog(@" days %d",day);
    [_daysremaining addObject:[NSString stringWithFormat:@"%d",day] ];
    }
    NSLog(@" days %@",_daysremaining);

私は何を間違っているのか、なぜ私は正しい日を取得していないのですか

4

3 に答える 3

1

コードをシンプルに保つ:

メソッドを使用して、計算ブロック内で呼び出すことができます。

- (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime{
    NSDate *fromDate;
    NSDate *toDate;

    NSCalendar *calendar=[NSCalendar currentCalendar];

    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];

    NSDateComponents *difference = [calendar components:NSDayCalendarUnit
        fromDate:fromDate toDate:toDate options:0];

    return [difference day];
}
于 2013-03-20T05:41:08.483 に答える