iOS - 生日字符串转化年龄

字数 29阅读 184

一.前言

 最近做一个智能幼教产品,需要通过出生年月计算儿童用户的年龄大小,写了一个简单的函数方法调用如下,希望能给有需要人有所帮助,不正之处望多指正!

pragma mark -- 生日转化为年龄

+(NSString *)countAgeWithBirthDay:(NSString *)birth{
//定义一个NSCalendar对象
NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *nowDate = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
//生日
NSDate *birthDay = [dateFormatter dateFromString:birth];

//用来得到详细的时差
unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;

NSDateComponents *date = [calendar components:unitFlags fromDate:birthDay toDate:nowDate options:0];

if([date year] >0)
{
    NSLog(@"%@",[NSString stringWithFormat:(@"%ld岁%ld月%ld天"),(long)[date year],(long)[date month],(long)[date day]]) ;
    return [NSString stringWithFormat:(@"%ld岁%ld月%ld天"),(long)[date year],(long)[date month],(long)[date day]] ;
}
else if([date month] >0)
{
    NSLog(@"%@",[NSString stringWithFormat:(@"%ld月%ld天"),(long)[date month],(long)[date day]]);
    return [NSString stringWithFormat:(@"%ld月%ld天"),(long)[date month],(long)[date day]] ;
}
else if([date day]>0){
    NSLog(@"%@",[NSString stringWithFormat:(@"%ld天"),(long)[date day]]);
    return [NSString stringWithFormat:(@"%ld天"),(long)[date day]] ;
}
else {
    NSLog(@"0天");
    return @"0" ;
}

}

推荐阅读更多精彩内容