Number of days between two NSDate objects

前端 未结 4 1432
悲&欢浪女
悲&欢浪女 2020-12-16 04:31

I\'m trying to compare two days of NSDate objects, I used at the first time NSDateComponents to calculate difference between my two dates Objects, but it is working correct

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 04:55

    NSString *start = @"2010-09-01";
    NSString *end = @"2010-12-01";
    
    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [f dateFromString:start];
    NSDate *endDate = [f dateFromString:end];
    [f release];
    
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];
    [gregorianCalendar release];
    

    components now holds the difference.

    NSLog(@"%ld", [components day]);
    

提交回复
热议问题