话不多说,直接上代码 /* *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; } },
js根据身份证号获取年龄,小于1岁的获取天数
最新推荐文章于 2024-07-02 16:04:04 发布