涉及到多年的地租 , 例如 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));