iOS 忽略时分秒计算时间差

一:常规方法

- (NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate{
    NSLog(@"start:%@", startDate);
    NSLog(@"end:%@", endDate);
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 
    unsigned int unitFlags = NSDayCalendarUnit;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate  toDate:endDate  options:0];
    return [comps day];
}

常规方法计算时间差,会被2个时间的时分秒所影响,打印时间如下
start:2014-01-19 04:15:22 +0000
end:2014-01-20 04:15:22 +0000
这样有可能会计算为0天。

二:强制计算方法

- (NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate{
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:startDate]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:stDt];
    stDt = [stDt dateByAddingTimeInterval: interval];
 
    interval = [zone secondsFromGMTForDate:endDt];
    endDt = [endDt dateByAddingTimeInterval:interval];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt  toDate:endDt  options:0];
    
    return [comps day];
}

你可能感兴趣的:(iOS 忽略时分秒计算时间差)