计算两个日期之间相差的天数(带带负数) 支持格式YYYY-mm-dd和YYYY-mm-dd HH:mm:ss

时间:2023-03-09 08:19:46
计算两个日期之间相差的天数(带带负数) 支持格式YYYY-mm-dd和YYYY-mm-dd HH:mm:ss
/**
* 计算两个日期之间相差的天数(带带负数) 支持格式YYYY-mm-dd比较
* @param higDate 减数
* @param lowDate 被减数
* @returns 差值天数 格式不正确返回null
* @dada 2016-09-19 lhh添加备注
*/
function DateDiff(higDate, lowDate) {
//sDate1和sDate2是2006-12-18格式
var aDate, oDate1, oDate2, iDays;
aDate = higDate.split("-");
oDate1 = new Date((aDate[1] + '-' + aDate[2] + '-' + aDate[0]).replace(/-/g, "/"));
//转换为12-18-2006格式
aDate = lowDate.split("-");
oDate2 = new Date((aDate[1] + '-' + aDate[2] + '-' + aDate[0]).replace(/-/g, "/"));
var diff = oDate1 - oDate2;
iDays = parseInt(diff / 1000 / 60 / 60 / 24);
//把相差的毫秒数转换为天数
if (isNaN(iDays)) return null;
return iDays;
}

 

/**
* 日期比较 支持格式YYYY-mm-dd HH:mm:ss比较
* @param Date1 日期1
* @param Date2 日期2
* @returns 差值(为0相等 正值 Date1 大于 Date2 负值相反) 格式不正确返回null
* @dada 2016-09-19 lhh添加备注
*/
function comptime(Date1, Date2) {
var higTimes = Date1.substring(0, 10).split('-');
var lowTimes = Date2.substring(0, 10).split('-');
higTime = higTimes[1] + '-' + higTimes[2] + '-' + higTimes[0] + ' ' + higDate.substring(10, 19);
lowTime = lowTimes[1] + '-' + lowTimes[2] + '-' + lowTimes[0] + ' ' + lowDate.substring(10, 19);
var num = (Date.parse(higTime) - Date.parse(lowTime)) / 3600 / 1000;
if (isNaN(num)) return null;
return num;
}
/**
* 两个日期的比较
* @param strDateStart
* @param strDateEnd
* @returns {Boolean}
*/
function twoDateSize(strDateStart, strDateEnd) {
var strSeparator = "-"; // 日期分隔符
var oDate1;
var oDate2;
var iDays;
oDate1 = strDateStart.split(strSeparator);
oDate2 = strDateEnd.split(strSeparator);
var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
//开始大于结束
if (strDateS > strDateE) {
return false;
} else {
return true;
}
}
function getDays(strDateStart, strDateEnd) {
var strSeparator = "-"; // 日期分隔符
var oDate1;
var oDate2;
var iDays;
oDate1 = strDateStart.split(strSeparator);
oDate2 = strDateEnd.split(strSeparator);
var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
return iDays;
}