失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > js根据出生日期计算年龄及根据年龄计算出生日期

js根据出生日期计算年龄及根据年龄计算出生日期

时间:2020-01-26 05:35:57

相关推荐

js根据出生日期计算年龄及根据年龄计算出生日期

1.根据日期算年龄

mymethod(birthday){//根据日期算年龄if(birthday){birthday=birthday.split('-');// 新建日期对象let date = new Date();// 今天日期,数组,同 birthdaylet today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];// 分别计算年月日差值let age = today.map((val, index) => {return val - birthday[index]})// 当天数为负数时,月减 1,天数加上月总天数if (age[2] < 0) {// 简单获取上个月总天数的方法,不会错let lastMonth = new Date(today[0], today[1], 0)age[1]--age[2] += lastMonth.getDate()}// 当月数为负数时,年减 1,月数加上 12if (age[1] < 0) {age[0]--age[1] += 12}console.log(age[0]+'岁'+age[1]+'月'+age[2]+'天');}}// mymethod(-08-08)

2.根据年龄算日期

myfunction(ageYear,ageMonth,ageDay){//根据年龄算日期var subYear = parseInt(ageYear); var subMonth = parseInt(ageMonth); var subDay = parseInt(ageDay); var now = new Date(); var nowYear = now.getFullYear(); var nowMonth = now.getMonth()+1; var nowDay = now.getDate(); // 按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。 var day = nowDay - subDay; var month = nowMonth - subMonth; var year = nowYear - subYear; // 检查是否溢出 if(day<=0){// 获得上月的天数 var lastMonth = nowMonth - 1; var lastMonthOfYear = nowYear; if(lastMonth<=0){lastMonth =lastMonth + 12 //(lastMonth + 12) % 12; lastMonthOfYear = lastMonthOfYear - 1;} day = day + new Date(lastMonthOfYear, lastMonth, 0).getDate(); month = month - 1; } if(month<=0){month =month + 12 //(month + 12) % 12; year--; } if(month<10){month='0'+month}if(day<10){day='0'+day}console.log(year+'-'+month+'-'+day);}// myfunction(1,10,20)

如果觉得《js根据出生日期计算年龄及根据年龄计算出生日期》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。