js根据身份证获取年龄,如果大于一岁,则显示几岁,如果小于一岁则显示几个月,如果小于一个月则显示几天

calculateAgeFromIdCard(idCardNumber) {
      // 假设身份证号码的格式是18位,且第7到14位是出生日期(YYYYMMDD)
      // 提取出生日期
      const birthYear = parseInt(idCardNumber.substr(6, 4))
      const birthMonth = parseInt(idCardNumber.substr(10, 2))
      const birthDay = parseInt(idCardNumber.substr(12, 2))

      // 获取当前日期
      const now = new Date()
      const currentYear = now.getFullYear()
      const currentMonth = now.getMonth() + 1 // 注意月份是从0开始的,所以要加1
      const currentDay = now.getDate()

      // 计算年龄
      let age = currentYear - birthYear
      let monthDiff = 0
      let dayDiff = 0

      // 如果当前月份小于出生月份,或者月份相同但当前日期小于出生日期,则年龄减一
      if (
        currentMonth < birthMonth ||
        (currentMonth === birthMonth && currentDay < birthDay)
      ) {
        age--
        monthDiff = 12 - birthMonth + currentMonth
      } else {
        monthDiff = currentMonth - birthMonth
      }

      // 如果月份差小于0,则年龄减一,并计算正确的月份差
      if (monthDiff < 0) {
        age--
        monthDiff += 12
      }

      // 计算天数差
      dayDiff = currentDay - birthDay

      // 如果天数差小于0,则月份减一,并计算正确的天数差(这里需要知道上个月的最后一天是哪一天)
      if (dayDiff < 0) {
        monthDiff--
        const lastDayOfMonth = new Date(
          currentYear,
          currentMonth - 1 - (monthDiff > 0 ? 1 : 0),
          0
        ).getDate()
        dayDiff = lastDayOfMonth + dayDiff
      }

      // 根据年龄、月份和天数差来格式化输出
      if (age > 0) {
        return age + '岁'
      } else if (monthDiff > 0) {
        return monthDiff + '个月'
      } else {
        return dayDiff + '天'
      }
    },
    // 示例使用  
const idCardNumber = "你的身份证号码"; // 替换为你的身份证号码  
console.log(calculateAgeFromIdCard(idCardNumber));
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值