计算两个日期之间相差的总天数,和 年月日数
function jisuan() {
var sDate1 = $("#create_begin").val();
var sDate2 = $("#create_end").val();
var d = getDay(sDate1, sDate2);
alert("相差" + d.y + "年" + d.m + "月" + d.d + "天" + d.day + "总天");
}
function getDay(sDate1, sDate2) {
var fixDate = function(sDate) {
var aD = sDate.split('-');
for (var i = 0; i < aD.length; i++) {
aD[i] = fixZero(parseInt(aD[i]));
}
return aD.join('-');
};
var fixZero = function(n) {
return n < 10 ? '0' + n: n;
};
var fixInt = function(a) {
for (var i = 0; i < a.length; i++) {
a[i] = parseInt(a[i]);
}
return a;
};
var getMonthDays = function(y, m) { // 获取月的天数
var aMonthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if ((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0)) {
aMonthDays[2] = 29;
}
return aMonthDays[m];
};
var getHoliday = function(date) { // 排除假期
var Holiday = ["2020-01-01", "2020-01-25", "2020-01-29", "2020-01-30", "2020-01-24", "2020-01-26", "2020-01-28", "2020-01-27", "2020-01-31", "2020-04-06", "2020-05-01", "2020-05-04", "2020-05-05", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-03", "2020-10-02", "2020-10-04", "2020-10-06", "2020-10-07", "2020-10-05", "2020-10-08"]; //全年节假日
for (var i = 0; i < Holiday.length; i++) {
if (Holiday[i] == date) {
return true;
}
}
return false;
}
//判断是否是周末
var get_day = function(nextDate) {
var day = new Date(nextDate).getDay(); //0-周日,6-周六
if (day == 0 || day == 6) {
return true;
}
return false;
}
var checkDate = function(sDate) {};
var y = 0;
var m = 0;
var d = 0;
var day = 0;
var sTmp;
var aTmp;
sDate1 = fixDate(sDate1);
sDate2 = fixDate(sDate2);
if (sDate1 > sDate2) {
return 'past'
}
var aDate1 = sDate1.split('-');
aDate1 = fixInt(aDate1);
var aDate2 = sDate2.split('-');
aDate2 = fixInt(aDate2);
//计算年份
y = aDate2[0] - aDate1[0];
if (sDate2.replace(aDate2[0], '') < sDate1.replace(aDate1[0], '')) {
y = y - 1;
}
//计算月份
aTmp = [aDate1[0] + y, aDate1[1], fixZero(aDate1[2])];
while (true) {
if (aTmp[1] == 12) {
aTmp[0]++;
aTmp[1] = 1;
} else {
aTmp[1]++;
}
if (([aTmp[0], fixZero(aTmp[1]), aTmp[2]]).join('-') <= sDate2) {
m++;
} else {
break;
}
}
//计算天数
aTmp = [aDate1[0] + y, aDate1[1] + m, aDate1[2]];
if (aTmp[1] > 12) {
aTmp[0]++;
aTmp[1] -= 12;
}
while (true) {
if (aTmp[2] == getMonthDays(aTmp[0], aTmp[1])) {
aTmp[1]++;
aTmp[2] = 1;
} else {
aTmp[2]++;
}
sTmp = ([aTmp[0], fixZero(aTmp[1]), fixZero(aTmp[2])]).join('-');
if (sTmp <= sDate2) {
if (!getHoliday(sTmp) && !get_day(sTmp)) {
d++;
}
} else {
break;
}
}
//计算总天数
aTmp = [aDate1[0], aDate1[1], aDate1[2]];
while (true) {
aTmp[2]++;
if (aTmp[2] == getMonthDays(aTmp[0], aTmp[1])) {
aTmp[1]++;
aTmp[2] = 1;
}
if (aTmp[1] > 12) {
aTmp[0]++; //
aTmp[1] -= 12;
}
sTmp = ([aTmp[0], fixZero(aTmp[1]), fixZero(aTmp[2])]).join('-');
if (sTmp <= sDate2) {
if (!getHoliday(sTmp) && !get_day(sTmp)) {
day++;
}
} else {
break;
}
}
return {
y: y,
m: m,
d: d,
day: day
}
}