js 计算两个日期格式字符串相差几年几个也几天

/**
 * @desc 计算年龄
 * 计算年份->计算月份->计算天数
 */
export const getDiffYmdBetweenDate = (sDate1, sDate2) => {
	var fixDate = function(sDate) {
		var aD = sDate.split('-');
		for (var i = 0; i < aD.length; i++) {
			aD[i] = fixZero(parseInt(aD[i]));
		}
		return aD.join('-');
	};
	var fixZero = function(n) {
		return n < 10 ? '0' + n : n;
	};
	var fixInt = function(a) {
		for (var i = 0; i < a.length; i++) {
			a[i] = parseInt(a[i]);
		}
		return a;
	};
	var getMonthDays = function(y, m) {
		var aMonthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if ((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0)) {
			aMonthDays[2] = 29;
		}
		return aMonthDays[m];
	};
	var checkDate = function(sDate) {};
	var y = 0;
	var m = 0;
	var d = 0;
	var sTmp;
	var aTmp;
	sDate1 = fixDate(sDate1);
	sDate2 = fixDate(sDate2);
	if (sDate1 > sDate2) {
		sTmp = sDate2;
		sDate2 = sDate1;
		sDate1 = sTmp;
	}
	var aDate1 = sDate1.split('-');
	aDate1 = fixInt(aDate1);
	var aDate2 = sDate2.split('-');
	aDate2 = fixInt(aDate2);
	y = aDate2[0] - aDate1[0];
	if (sDate2.replace(aDate2[0], '') < sDate1.replace(aDate1[0], '')) {
		y = y - 1;
	}
	//计算月份
	aTmp = [aDate1[0] + y, aDate1[1], fixZero(aDate1[2])];
	while (true) {
		if (aTmp[1] == 12) {
			aTmp[0]++;
			aTmp[1] = 1;
		} else {
			aTmp[1]++;
		}
		if (([aTmp[0], fixZero(aTmp[1]), aTmp[2]]).join('-') <= sDate2) {
			m++;
		} else {
			break;
		}
	}
	//计算天数
	aTmp = [aDate1[0] + y, aDate1[1] + m, aDate1[2]];
	if (aTmp[1] > 12) {
		aTmp[0]++;
		aTmp[1] -= 12;
	}
	while (true) {
		if (aTmp[2] == getMonthDays(aTmp[0], aTmp[1])) {
			if (aTmp[1] == 12) {
				aTmp[0]++;
				aTmp[1] = 1;
				aTmp[2] = 1;
			} else {
				aTmp[1]++;
				aTmp[2] = 1;
			}
		} else {
			aTmp[2]++;
		}
		sTmp = ([aTmp[0], fixZero(aTmp[1]), fixZero(aTmp[2])]).join('-');
		if (sTmp <= sDate2) {
			d++;
		} else {
			break;
		}
	}
	
	// 返回多少年多少月多少天
	if(y == 0){
		if(m == 0){
			if(d == 0){
				return '就是今天';
			}else{
				return d + '天';
			}
		}else{
			if(d == 0){
				return '刚好' + m + '个月';
			}else{
				return m + '个月' + d + '天';
			}
		}
	}else{
		if(m == 0){
			if(d == 0){
				return '刚好' + y + '年';
			}else{
				return y + '年' + d + '天';
			}
		}else{
			if(d == 0){
				return '刚好' + y + '年' + m + '个月';
			}else{
				return y + '年' + m + '个月' + d + '天';
			}
		}
	}
}
posted @ 2023-01-05 11:43  合起来的彳亍  阅读(218)  评论(0编辑  收藏  举报