?比如:2023-1-1? 至? 2023-12-31 之间,间隔12个月;
1.向下取整(一般都是向下取整)
function calculateMonthDifference(startDateString, endDateString) {
var start = new Date(startDateString); // 将起始日期字符串转换为Date对象
var end = new Date(endDateString); // 将结束日期字符串转换为Date对象
var timeDiff = Math.abs(end.getTime() - start.getTime()); // 获取时间差(单位:毫秒)
var monthDiff = Math.floor(timeDiff / (30 * 24 * 60 * 60 * 1000)); // 根据每个月平均天数进行近似计算
return monthDiff; // 返回月份差值
}
var startDate = "2023-1-1";
var endDate = "2023-12-31";
var result = calculateMonthDifference(startDate, endDate);
console.log("时间间隔月数:" + result);
2.向上取整
function calculateMonthDifference(startDateString, endDateString) {
var start = new Date(startDateString); // 将起始日期字符串转换为Date对象
var end = new Date(endDateString); // 将结束日期字符串转换为Date对象
var timeDiff = Math.abs(end.getTime() - start.getTime()); // 获取时间差(单位:毫秒)
var monthDiff = Math.ceil(timeDiff / (30 * 24 * 60 * 60 * 1000)); // 根据每个月平均天数进行近似计算
return monthDiff; // 返回月份差值
}
var startDate = "2023-1-1";
var endDate = "2023-12-31";
var result = calculateMonthDifference(startDate, endDate);
console.log("时间间隔月数:" + result);
自用代码备份)
watch(
() => props.visible,
(visible) => {
if (visible) {
if (props.data) {
assignObject(form, {
...props.data,
});
form.startTime = form.startTime.split('T')[0].replace(/-/g, "/")
form.endTime = form.endTime.split('T')[0].replace(/-/g, "/")
function calculateMonthDifference(startDateString, endDateString) {
var start = new Date(startDateString); // 将起始日期字符串转换为Date对象
var end = new Date(endDateString); // 将结束日期字符串转换为Date对象
var timeDiff = Math.abs(end.getTime() - start.getTime()); // 获取时间差(单位:毫秒)
var monthDiff = Math.floor(timeDiff / (30 * 24 * 60 * 60 * 1000)); // 根据每个月平均天数进行近似计算
return monthDiff; // 返回月份差值
}
var startDate = form.startTime;
var endDate = form.endTime;
var result = calculateMonthDifference(startDate, endDate);
console.log("时间间隔月数:" + result);
form.jg = result
isUpdate.value = true;
loadingData()
} else {
isUpdate.value = false;
loadingData()
}
} else {
resetFields();
}
}
);