美文网首页藤原とうふ店(自家用)
iOS 根据身份证号获取出生日期,并计算年龄

iOS 根据身份证号获取出生日期,并计算年龄

作者: 宏炜 | 来源:发表于2018-11-26 14:11 被阅读123次

根据身份证号获取出生日期,并计算年龄: 90与00后均可计算

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *str = @"611421199308261248";

    //获取出生日期
    NSString *dateStr = [self subsIDStrToDate:str];
     NSLog(@"dateStr == %@",dateStr);
   
    //获取年龄
    NSString *ageStr = [self calculateAgeStr:str];
    NSLog(@"ageStr == %@",ageStr);
    
}
截取身份证的出生日期并转换为日期格式:
//截取身份证的出生日期并转换为日期格式
-(NSString *)subsIDStrToDate:(NSString *)str{
    NSMutableString *result = [NSMutableString stringWithCapacity:0];
    
    NSString *dateStr = [str substringWithRange:NSMakeRange(6, 8)];
    NSString  *year = [dateStr substringWithRange:NSMakeRange(0, 4)];
    NSString  *month = [dateStr substringWithRange:NSMakeRange(4, 2)];
    NSString  *day = [dateStr substringWithRange:NSMakeRange(6,2)];
    
    [result appendString:year];
    [result appendString:@"-"];
    [result appendString:month];
    [result appendString:@"-"];
    [result appendString:day];
    
    return result;
}
根据出生日期计算年龄:
//计算年龄
-(NSString *)calculateAgeStr:(NSString *)str{
  //截取身份证的出生日期并转换为日期格式
   NSString *dateStr = [self subsIDStrToDate:str];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-mm-dd";
    NSDate *birthDate =  [formatter dateFromString:dateStr];
    NSTimeInterval dateDiff = [birthDate timeIntervalSinceNow];
    
    // 计算年龄
    int age  =  trunc(dateDiff/(60*60*24))/365;
    NSString *ageStr = [NSString stringWithFormat:@"%d", -age];

    return ageStr;
}

打印结果:

dateStr == 1993-08-26
ageStr == 25

相关文章

网友评论

    本文标题:iOS 根据身份证号获取出生日期,并计算年龄

    本文链接:https://www.haomeiwen.com/subject/qzhbqqtx.html