感谢@Zazerat 在这篇文章中的回答
我想出了一个解决方案。@Jazerat 提供了 JSDate 的精简版本,我将其包括在内,以便轻松调整日期的月份。这是最终的代码:
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
var y = this.getFullYear();
return (((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0));
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function calculateLeasePeriod(){
var startDateValue=document.forms[0].StartDate.value;
var endDateValue=document.forms[0].EndDate.value;
if (endDateValue!="" && startDateValue!=""){
var startDateArray=startDateValue.split("/");
var endDateArray=endDateValue.split("/");
var startDate= new Date(startDateArray[2], startDateArray[1], startDateArray[0]);
var endDate= new Date(endDateArray[2], endDateArray[1], endDateArray[0]);
var diffYears = endDate.getFullYear()-startDate.getFullYear();
var diffMonths = endDate.getMonth()-startDate.getMonth();
var diffDays = endDate.getDate()-startDate.getDate();
var months = ((diffYears*12) + diffMonths);
if (diffDays<0){
months=months-1;
var adjStartDate = startDate.addMonths(months);
diffDays = endDate.getDate()-adjStartDate.getDate();
if (diffDays<0){
diffDays=daysInMonth(adjStartDate.getMonth(), adjStartDate.getYear())+ diffDays;
}
}
$("#PrimaryLeasePeriod").html(months + " months and " + diffDays + " days");
}else{
$("#PrimaryLeasePeriod").html("");
}
}
我希望其他人觉得这很有用!