Calculating the age of a person using two NSDates

你说的曾经没有我的故事 提交于 2019-12-01 01:19:11
Gabriele Petronella

There are a couple of things that can be noted. First of all, the code for computing the age is fine, except that I don't understand why you return NSDateComponents instead of just the age in years.

Here's how I would do it

- (NSInteger)age {
    NSDate *today = [NSDate date];
    NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
                                       components:NSYearCalendarUnit
                                       fromDate:self.dob
                                       toDate:today
                                       options:0];
    return ageComponents.year;
}

You are interested only in the year component, so return it instead of NSDateComponents. Using self.dob instead of an argument gets the date you set earlier.

Just created a simple method that returns the age in years as a string.

-(NSString *) getAge:(NSDate *)dateOfBirth {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierIndian];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit
                                               fromDate:dateOfBirth
                                                 toDate:[NSDate date]
                                                options:0];

    return [NSString stringWithFormat:@"%li",components.year];
    }

NOTE

  1. This uses Indian Calendar - change it if u wish.
  2. To call NSString *yearsOldinString = [self getAge:dateOfBirth];, where dateOfBirth represents person's date of birth in NSDate format.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!