计算年龄,精确到年月日
/**
* 计算年龄
* @param{string} start 2019-11-1
* @param{string} end 2019-11-1
* >5,岁;<5 岁,月,天;<1y,月,天;<1m,天
*/
const getMothDay = function(year,mouth){
return new Date(year,mouth-1,0).getDate()
}
const getAge = function(start,end){
let result = ''
let sy = start.split('-')[0]
let sm = start.split('-')[1]
let sd = start.split('-')[2]
let ey = end.split('-')[0]
let em = end.split('-')[1]
let ed = end.split('-')[2]
let dy = ey - sy
let dm = em - sm
let dd = ed - sd
switch (true){
case dy >= 5:
result = dy + '年';
console.log('dy >= 5')
break;
case dy < 5 && dy >=1:
if(dd < 0) {
dm = dm -1
}
if(dm<0) {
dy = dy-1;
dm = 12 + dm
result = dy + '岁' + dm + '月';
} else if(dm > 0){
result = dy + '岁' + dm + '月';
} else {
result = dy + '岁';
}
if(dd < 0) {
dd = getMothDay(sy, sm) + dd
result = dy + '岁' + dm + '月' + dd + '天';
} else if(dd > 0) {
result = dy + '岁' + dm + '月' + dd + '天';
} else {
result = dy + '岁' + dm + '月';
}
console.log('dy < 5 && dy >=1:')
break;
case (dy < 1):
if(dd < 0) {
dm = dm -1
}
if(dm > 0){
result = dm + '月';
}
if(dd < 0) {
dd = getMothDay(sy, sm) + dd
result = result + dd + '天';
} else if(dd > 0) {
result = result + dd + '天';
} else {
result = dd + '天'
}
break;
default:
result = '-1'
break;
}
return result
}
本文来自博客园,作者:东庄,转载请注明原文链接:https://www.cnblogs.com/lizhiwei8/p/11822232.html