已知年龄通过js计算出生年月
列 【5岁6个月15天】,
算出生日期
一年十二月,月份位做十二进制减法即可,不足借一,一当12,如:1减4,不够,借一,1+12-4=9
已知年龄通过js计算出生年月
列 【5岁6个月15天】,
算出生日期
一年十二月,月份位做十二进制减法即可,不足借一,一当12,如:1减4,不够,借一,1+12-4=9
function getBirthDay(age){
// 转换为数字
const subYear = parseInt(age.substring(age.indexOf("岁")-1));
const subMonth = parseInt(age.substring(age.indexOf("月")-1));
const subDay = parseInt(age.substring(age.indexOf("日")-1));
const now = new Date();
const nowYear = now.getFullYear();
const nowMonth = now.getMonth();
const nowDay = now.getDay();
// 按照减法原理,先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) % 12;
lastMonthOfYear = lastMonthOfYear - 1;
}
day = day + new Date(lastMonthOfYear, lastMonth, 0 ).getDate();
month = month - 1;
}
if(month<0){
month = (month + 12) % 12;
year--;
}
console.log(year+'年'+month+'月'+day+'日')
}
getBirthDay("2岁3月8日");