报销标准计算公式跨月边界处理
调试之前出现要么开始月多一天或者少一天,要么结束时间多一天少一天,累计计算金额总是有缺陷,都是跨月边界没处理好。
话不多说,整块代码直接lu起来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>出差费用计算</title>
<script>
function calculateTravelExpenses() {
// 假设整月的出差费用是1000元
const monthlyExpense = 1000;
// 获取表单输入
const startDateStr = document.getElementById('startDate').value;
const endDateStr = document.getElementById('endDate').value;
// 解析日期
const startDate = new Date(startDateStr);
const endDate = new Date(endDateStr);
// 验证日期
if (startDate > endDate) {
alert('开始日期必须在结束日期之前或相同!');
return;
}
let totalExpense = 0;
let currentDate = new Date(startDate);
let currentMonth = startDate.getMonth();
let currentYear = startDate.getFullYear();
while (currentDate <= endDate) {
// 获取当前月份的天数
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
// 计算当前月份的开始和结束日期
const monthStartDate = new Date(currentYear, currentMonth, 1);
let monthEndDate = new Date(currentYear, currentMonth + 1, 0);
// 如果结束日期在当前月份之前,则调整结束日期
if (endDate < monthEndDate) {
monthEndDate = new Date(endDate);
}
// 计算出差天数
let travelDays = Math.round((monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24) + 1);
// 如果开始日期在当前月份之后,则调整出差天数
if (startDate > monthStartDate) {
travelDays -= (startDate - monthStartDate) / (1000 * 60 * 60 * 24);
}
// 如果结束日期在当前月份之前,则进一步调整出差天数
if (endDate < monthEndDate) {
travelDays -= (monthEndDate - endDate) / (1000 * 60 * 60 * 24);
}
debugger;
// 计算出差费用
if (travelDays >= daysInMonth || Math.round(travelDays) === daysInMonth) {
// 整月出差,按照整月费用计算
totalExpense += monthlyExpense;
} else {
// 非整月出差,按照天数计算
const dailyExpense = monthlyExpense / daysInMonth;
totalExpense += dailyExpense * travelDays;
}
// 更新日期到下个月的第一天
currentDate.setMonth(currentMonth + 1, 1);
currentMonth = currentDate.getMonth();
currentYear = currentDate.getFullYear();
}
// 显示结果
document.getElementById('results').textContent = `总出差天数: ${(endDate - startDate) / (1000 * 60 * 60 * 24) + 1}\n总出差金额: ${totalExpense.toFixed(2)}`;
}
</script>
</head>
<body>
<h1>出差费用计算</h1>
<form>
<label for="startDate">开始日期:</label>
<input type="date" id="startDate" required>
<label for="endDate">结束日期:</label>
<input type="date" id="endDate" required>
<button type="button" onclick="calculateTravelExpenses()">计算</button>
</form>
<div id="results" style="margin-top: 20px;"></div>
</body>
</html>