IOS中根据生日精确计算年龄

- (IBAction)calc {
    //年齢計算
    NSDate *birthday = birthdayPicker.date;
    NSDate *today = [NSDate date]; 
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   
    NSUInteger unitFlags;
    switch (unitControl.selectedSegmentIndex) {
        case 0:
            unitFlags = NSYearCalendarUnit;
            break;
        case 1:
            unitFlags = NSMonthCalendarUnit;
            break;
        case 2:
            unitFlags = NSDayCalendarUnit;
            break;
            
        default:
            break;
    }
    
    
    NSDateComponents *components = [gregorian components:unitFlags fromDate:birthday toDate:today options:0];
    
    //距现在多少年、月、日
    NSInteger age;
    switch (unitFlags) {
        case NSYearCalendarUnit:
            age = [components year];
            break;
        case NSMonthCalendarUnit:
            age = [components month];
            break;
        case NSDayCalendarUnit:
            age = [components day];
            break;
            
    }
    
    
    resultLabel.text = [NSString stringWithFormat:@"%d",age];

}

你可能感兴趣的:(ios开发)