iOS - 身份证号判断
#pragma mark - 身份证识别
+(BOOL)checkIdentityCardNo:(NSString*)cardNo;
//根据身份证号获取性别
+(NSInteger)getIdentityCardSex:(NSString *)numberStr;
//根据身份证号获取年龄
+(NSString *)getIdentityCardAge:(NSString *)numberStr;
#pragma mark - 身份证识别
+(BOOL)checkIdentityCardNo:(NSString*)cardNo
{
if (cardNo.length != 18) {
return NO;
}
NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
int val;
BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
if (!isNum) {
return NO;
}
int sumValue = 0;
for (int i =0; i<17; i++) {
sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
}
NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
return YES;
}
return NO;
}
//根据身份证号获取性别
+(NSInteger)getIdentityCardSex:(NSString *)numberStr
{
int sexInt=[[numberStr substringWithRange:NSMakeRange(16,1)] intValue];
if(sexInt%2!=0)
{
return 1;
}
else
{
return 0;
}
}
//根据身份证号获取年龄
+(NSString *)getIdentityCardAge:(NSString *)numberStr
{
NSDateFormatter *formatterTow = [[NSDateFormatter alloc]init];
[formatterTow setDateFormat:@"yyyy-MM-dd"];
NSString* dataString =[self birthdayStrFromIdentityCard:numberStr];
NSDate *bsyDate = [formatterTow dateFromString:dataString];
NSTimeInterval dateDiff = [bsyDate timeIntervalSinceNow];
int age = trunc(dateDiff/(60*60*24))/365;
return [NSString stringWithFormat:@"%d",-age];
}
//根据身份证号获取生日
+(NSString *)birthdayStrFromIdentityCard:(NSString *)numberStr
{
NSMutableString *result = [NSMutableString stringWithCapacity:0];
NSString *year = nil;
NSString *month = nil;
BOOL isAllNumber = YES;
NSString *day = nil;
if([numberStr length]<14)
return result;
//**截取前14位
NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(0, 13)];
//**检测前14位否全都是数字;
const char *str = [fontNumer UTF8String];
const char *p = str;
while (*p!='\0') {
if(!(*p>='0'&&*p<='9'))
isAllNumber = NO;
p++;
}
if(!isAllNumber)
return result;
year = [numberStr substringWithRange:NSMakeRange(6, 4)];
month = [numberStr substringWithRange:NSMakeRange(10, 2)];
day = [numberStr substringWithRange:NSMakeRange(12,2)];
[result appendString:year];
[result appendString:@"-"];
[result appendString:month];
[result appendString:@"-"];
[result appendString:day];
return result;
}