0CODE.CC-零代码社区

【代码块】适用于租赁行业的复杂租期计算规则

很多企业场景下会存在需要进行财务周期统计的计算规则,如果时间单纯的是以天数差计算可以采用采用公式函数计算,但是涉及到一种非常特殊的财务计算场景:

跨月计算时任意两个时间点终止日期比起始日期的天少1的情况下计算为整月,例如2月15日到4月14日,计算为2个月,2月15日到4月15日为2个月零1天。

这种场景下,如果采用公式函数计算会非常非差,要考虑中间大月、小月、特殊月的天数差,要将间隔月份的所有天数差计算出来之后再来补偿到最终计算结果!但是我们可以用代码块快速进行过程计算并输出结果:

function getNextMonthSameTime(date) {
	// 获取当前月份和年份
	var currentMonth = date.getMonth();
	var currentYear = date.getFullYear();

	// 如果当前月份是12月,则下个月月份为1,年份加1
	if (currentMonth === 11) {
		currentMonth = 0;
		currentYear++;
	} else {
		currentMonth++;
	}

	// 创建一个新的 Date 对象,使用下个月的月份和当前日期的日期和时间
	var nextMonthDate = new Date(currentYear, currentMonth, date.getDate() - 1, date.getHours(), date.getMinutes(), date.getSeconds());

	return nextMonthDate;
}

function getDateDiff(startDate, endDate) {
	var diff = Math.abs(endDate.getTime() - startDate.getTime()); // 获取两个日期的毫秒数差值
	var days = Math.floor(diff / (24 * 60 * 60 * 1000)); // 计算天数
	var hours = Math.floor(diff / (60 * 60 * 1000)) % 24; // 计算小时数
	var minutes = Math.floor(diff / (60 * 1000)) % 60; // 计算分钟数
	var seconds = Math.floor(diff / 1000) % 60; // 计算秒数

	return {
		days: days,
		hours: hours
	};
}

function calculateDuration(startDate, endDate) {

	let monthArray = []

	let lastMonthDate = new Date(startDate)

	while (lastMonthDate.getTime() < new Date(endDate).getTime()) {

		lastMonthDate = getNextMonthSameTime(lastMonthDate)

		if (lastMonthDate.getTime() <= new Date(endDate).getTime()) {
			monthArray.push(lastMonthDate)
		}

		lastMonthDate = new Date(lastMonthDate.getFullYear(), lastMonthDate.getMonth(), lastMonthDate.getDate() + 1, lastMonthDate.getHours(), lastMonthDate.getMinutes(), lastMonthDate.getSeconds())

	}

	var _startDate = new Date(startDate)

	if (monthArray.length > 0) {
		_startDate = monthArray[(monthArray.length - 1)]
	}

	var dateDiff = getDateDiff(_startDate, new Date(endDate))

	return {
		months: monthArray.length,
		days: dateDiff.days,
		hours: dateDiff.hours
	};
}

// 测试示例
const result = calculateDuration(qf_field.{起是时间$$1A3CD880B$$},qf_field.{终止时间$$1A3CD880C$$});
qf_output = {result}

注1:qf_field.{起始时间$$1A3CD880B$$} 字段替换为表单起始时间字段

注2:qf_field.{终止时间$$1A3CD880C$$} 字段替换为表单终止时间字段 

请登录后发表评论

      • gouxiang的头像0CODE.CC-零代码社区0code.cc构想世界徽章-初出茅庐0CODE.CC-零代码社区0code.cc等级-LV10CODE.CC-零代码社区0code.cc作者超级版主0