例子,js计算相差的月份与天数。
//计算月份差
function getMonthNumber(date1,date2){
//默认格式为"20030303",根据自己需要改格式和方法
var year1 = date1.substr(0,4);
var year2 = date2.substr(0,4);
var month1 = date1.substr(4,2);
var month2 = date2.substr(4,2);
var len=(year2-year1)*12+(month2-month1);
return len;
}
var len=getMonthNumber('200403','200504');
//alert('2003-03-03'.replace(/-/g, "/"));
//alert('2003-03-03'.replace(/-/g, ""));
if(len<0){
alert("查询起始月份不能比查询终止月份大.");
}else if(len >11){
alert("查询月份时间段不能超过12个月.");
}
//计算天数差
function getDayNumber(date1,date2){
//默认格式为"20030303",根据自己需要改格式和方法
var year1 = date1.substr(0,4);
var year2 = date2.substr(0,4);
var month1 = date1.substr(4,2);
var month2 = date2.substr(4,2);
// www.jb200.com
var day1 = date1.substr(6,2);
var day2 = date2.substr(6,2);
temp1 = year1+"/"+month1+"/"+day1;
temp2 = year2+"/"+month2+"/"+day2;
var dateaa= new Date(temp1);
var datebb = new Date(temp2);
var date = datebb.getTime() - dateaa.getTime();
var time = Math.floor(date / (1000 * 60 * 60 * 24));
alert(time);
}
getDayNumber('20030303','20040503');