根据身份证号计算年龄

function getIdcardAge(idcard) {
  var len = (idcard + "").length;
  if (len == 0) {
    return 0;
  } else {
    if ((len != 15) && (len != 18)) {
      return 0;
    }
  }
  var strBirthday = "";
  if (len == 18) {
    strBirthday = idcard.substr(6, 4) + "/" + idcard.substr(10, 2) + "/" + idcard.substr(12, 2);
  }
  if (len == 15) {
    strBirthday = "19" + idcard.substr(6, 2) + "/" + idcard.substr(8, 2) + "/" + idcard.substr(10,
      2);
  }
  //时间字符串里,必须是“/”
  var birthDate = new Date(strBirthday);
  var nowDateTime = new Date();
  var age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
  if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime
    .getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

在Vue中,根据身份证号计算年龄可以通过以下步骤实现: 1. **获取身份证号**:从用户输入或其他数据源获取身份证号。 2. **解析出生日期**:根据身份证号提取出生日期(通常是身份证号的第7到14位)。 3. **计算年龄**:使用JavaScript的日期处理功能计算年龄。 以下是一个示例代码,展示了如何在Vue组件中实现这一功能: ```html <template> <div> <input v-model="idNumber" placeholder="请输入身份证号" /> <button @click="calculateAge">计算年龄</button> <p>年龄: {{ age }}</p> </div> </template> <script> export default { data() { return { idNumber: '', age: '' }; }, methods: { calculateAge() { const idNumber = this.idNumber; if (idNumber.length === 18) { const birthDate = idNumber.substring(6, 14); const year = parseInt(birthDate.substring(0, 4)); const month = parseInt(birthDate.substring(4, 6)); const day = parseInt(birthDate.substring(6, 8)); const birthDateObj = new Date(year, month - 1, day); const today = new Date(); let age = today.getFullYear() - birthDateObj.getFullYear(); const monthDifference = today.getMonth() - birthDateObj.getMonth(); if ( monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDateObj.getDate()) ) { age--; } this.age = age; } else { this.age = '身份证号格式不正确'; } } } }; </script> ``` 在这个示例中: 1. **数据绑定**:使用`v-model`指令将输入框的值绑定到`idNumber`数据属性。 2. **事件处理**:点击按钮时触发`calculateAge`方法。 3. **计算年龄**:`calculateAge`方法解析出生日期并计算年龄
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值