我想从出生日期的数组中剩余几天我正在使用以下代码
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);
我做错了为什么我没有得到正确的日子
答案 0 :(得分:2)
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);
day = day -1;
NSLog(@" _newlymadeArray %@",[_convertedBdates objectAtIndex:i]);
NSLog(@" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:@"%d",day] ];
}
NSLog(@" days %@",_daysremaining);
答案 1 :(得分:2)
尝试这样会对你有帮助,
NSString *start = @"03/12/2013";
NSString *end = @"09/12/2013";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"dd/mm/yyyy"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
NSLog(@"%d",[components day]);
答案 2 :(得分: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];
}