在Facebook API iOS中将生日转换为年龄

时间:2015-08-11 16:52:02

标签: ios facebook-sdk-4.x

我想将用户的年龄显示为字符串。我正在使用Facebook API,我只看到生日的日期而不是年龄值。是否可以将bithday转换为年龄?这是我使用生日的代码:

[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
                                                                    parameters:@{ @"fields" : @"id,birthday)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            NSString *ageOfLoginUser = [result valueForKey:@"birthday"];

            self.age.text = ageOfLoginUser;
        }
    }];

1 个答案:

答案 0 :(得分:0)

正如上面的评论中所述,您应该查看以下代码:How to calculate the age based on NSDate

NSString *birthDate = @"03/31/1990";    
NSDate *todayDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
int time = [todayDate timeIntervalSinceDate:[dateFormatter dateFromString:birthDate]];
int allDays = (((time/60)/60)/24);
int days = allDays%365;
int years = (allDays-days)/365;

NSLog(@"You live since %i years and %i days",years,days);