1. 程式人生 > >iOS 計算日期間隔天數 —— HERO部落格

iOS 計算日期間隔天數 —— HERO部落格

計算兩個日期間隔天數,下面貼上程式碼,計算指定日期與當前日期間隔天數:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    NSInteger *days = [self computeDaysWithDataFromString:@"2016-04-24"];
    NSLog(@"days=%ld", days);
}

//計算日期間隔天數
- (NSInteger)computeDaysWithDataFromString:(NSString *)string
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:2];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:string]];
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
    NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents.day;
}