js根据身份证号获取年龄,小于1岁的获取天数

话不多说,直接上代码
/*
*certificateNum:身份证号码
*/
function calculateAge(certificateNum){
   let birthYearSpan = certificateNum.length === 15 ? 2 : 4;
   let year = (birthYearSpan === 2 ? '19' : '') + certificateNum.substr(6, birthYearSpan);
   let month = certificateNum.substr(6 + birthYearSpan, 2);
   let day = certificateNum.substr(8 + birthYearSpan, 2);

   let now = new Date(); 
   let monthFloor = ((now.getMonth() + 1) < parseInt(month, 10)
      || (now.getMonth() + 1) === parseInt(month, 10) && now.getDate() < parseInt(day, 10)) ? 1 : 0;
   let age = now.getFullYear() - parseInt(year, 10) - monthFloor;
   
  if(age===0){
      //年龄小于1岁,计算天数。注意:此处必须使用new Date('yyyy/mm/dd')这种格式,将字符串转换为Date类型。
        如果用 new Date('yyyy-mm-dd')这种,会存在兼容性问题,在Chrome下好使,其它浏览器不好使。
        可以采用new Date(Date.parse(str.replace(/-/g,"/")))将yyyy-mm-dd转换为yyyy/mm/dd。       let diffDay = Math.floor((new Date().getTime() - new Date(year+'/'+month+'/'+day+" 00:00:00").getTime())/(24*60*60*1000));  
       return diffDay;
     }else{
       return age;
     }
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值