涉及到多年的地租 , 例如 2024年5月15日 - 2026年5月15日 , 总承包租金是60000
假设 当前年是2024年 , 则计算2024年5月15日-2024年12月31日的租金收入 , 如果是2025年则是2025年1月1日-2025年12月31日
//示例交易数据 var transactions = [ { type: "转出土地收益", money: 37400, start: "2024-06-07", end: "2025-06-07" }, { type: "转入土地支出", money: 400, start: "2024-06-07", end: "2025-06-07" } ]; function calculateYearlyNetAmount(transactions, year) { var totalIncome = 0; // 总收益 var totalExpense = 0; // 总支出 transactions.forEach(function(transaction) { var startDate = new Date(transaction.start); var endDate = new Date(transaction.end); // 判断交易是否在今年内发生 var yearStartDate = new Date(year, 0, 1); // 当年的第一天 var yearEndDate = new Date(year, 11, 31, 23, 59, 59, 999); // 当年的最后一天(精确到毫秒) if (startDate <= yearEndDate && endDate >= yearStartDate) { // 计算今年内交易开始和结束的日期 var startDateInYear = startDate > yearStartDate ? startDate : yearStartDate; var endDateInYear = endDate < yearEndDate ? endDate : yearEndDate; // 计算今年内的天数 var daysInYear = (endDateInYear - startDateInYear) / (1000 * 60 * 60 * 24); // 如果交易完全在今年内,则使用原始金额 // 否则,根据今年内的天数计算部分金额 var yearlyAmount = (startDateInYear === startDate && endDateInYear === endDate) ? transaction.money : (transaction.money * daysInYear / ((endDate - startDate) / (1000 * 60 * 60 * 24))); // 累加总收益或总支出 if (transaction.type === "转出土地收益") { totalIncome += yearlyAmount; } else if (transaction.type === "转入土地支出") { totalExpense += yearlyAmount; } } }); // 计算并返回净金额 return {inMoney : totalIncome , outMoney : totalExpense , finalMoney : (totalIncome - totalExpense).toFixed(2)};}console.log(calculateYearlyNetAmount(transactions , 2024));