根据身份证号码获取生日、年龄、性别

根据身份证号码获取生日、年龄、性别

  1. 判断是否是身份证号码
  2. 获取生日日期
  3. 通过生日计算年龄
  4. 性别判断
// 判断身份证号是否合法
function isCard (str){
	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	return reg.test(str);
}
// 通过身份证号获取生日日期
function GetBirthday (identityCard){
	var len = (identityCard + “”).length;
	var strBirthday = "";
	if (!isCard (identityCard)){
		return false;
	}
	 if (len == 0){
	 	return false;
	 } else {
	 	// 身份证号码只能为15位或18位其它不合法
	 	if ((len != 15) && (len != 18)){
	 		return false;
	 	}
	 }
	 // 处理18位的身份证号码从号码中得到生日和性别代码
	 if (len == 18){
         strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
      }
      if (len == 15) {
          strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
      }
      // 时间字符串里,必须是“/”
      return new Date(strBirthday);
}
// 根据身份证号获取年龄
function GetAge(identityCard){
	var nowDateTime = new Date();
	var age = 0;
	var birthDate = GetBirthday(identityCard);
	if (birthDate){
		age = nowDateTime.getFullYear() - birthDate.getFullYear();
		// 再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
		if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
            age--;
          }
	}else{
		return age;
	}
}
// 根据身份证号码获取性别
function GetSex(card){
	// 获取性别
    if (parseInt(card.substr(16, 1)) % 2 == 1) {
        return 0;//男
    } else {
       return 1;//女
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值