这里有两种方法,第一种方法是只能到日期,个人认为第二种比较好一点,什么都可以(只是不知有没有闰年,第一个
方法1:
<html>
<head>
<script language=javascript>
//判断年份是否是闰年
function isLeapYear(year){
if(year%400==0){
return false;
}else if(year%4==0){
return true;
}else{
return false;
}
}
//计算两个日期的差值
function get()
{
var d1 = document.getElementById("id1").value;
var d2 = document.getElementById("id2").value;
compareDate(d1,d2)
}
function compareDate(date1,date2)
{
var regexp=/^(/d{1,4})[-|/.]{1}(/d{1,2})[-|/.]{1}(/d{1,2})$/;
var monthDays=[0,3,0,1,0,1,0,0,1,0,0,1];
regexp.test(date1);
var date1Year=RegExp.$1;
var date1Month=RegExp.$2;
var date1Day=RegExp.$3;
regexp.test(date2);
var date2Year=RegExp.$1;
var date2Month=RegExp.$2;
var date2Day=RegExp.$3;
firstDate=new Date(date1Year,date1Month,date1Day);
secondDate=new Date(date2Year,date2Month,date2Day);
result=Math.floor((secondDate.getTime()-firstDate.getTime())/(1000*3600*24));
for(j=date1Year;j<=date2Year;j++){
if(isLeapYear(j)){
monthDays[1]=2;
}else{
monthDays[1]=3;
}
for(i=date1Month-1;i<date2Month;i++){
result=result-monthDays[i];
}
}
return result;
}
//计算日期加上天数后的日期
function addDays(date1,days){
var monthDays=[0,3,0,1,0,1,0,0,1,0,0,1];
var regexp=/^(/d{1,4})[-|/.]{1}(/d{1,2})[-|/.]{1}(/d{1,2})$/;
regexp.test(date1);
var date1Year=RegExp.$1;
var date1Month=RegExp.$2;
var date1Day=RegExp.$3;
firstDate=new Date(date1Year,date1Month,date1Day);
firstDate.setTime(firstDate.getTime()+days*1000*3600*24);
var diff=0;
for(j=date1Year;j<=firstDate.getYear();j++){
if(isLeapYear(j)){
monthDays[1]=2;
}else{
monthDays[1]=3;
}
for(i=date1Month-1;i<firstDate.getMonth()-1;i++){
diff=diff+monthDays[i];
}
}
result=firstDate.getYear()+"-"+firstDate.getMonth()+"-"+firstDate.getDate();
if(diff!=0){
result=addDays(result,diff);
}
return result;
}
</script>
</head>
<body>
<input type=text value="2007-02-04" id=id1>
<input type=text value="2007-03-04" id = id2>
<input type=button id=bt value="OK" οnclick="get()">
</body>
</html>
方法2
function GetdataBetween(datastart,dataend)
{
//var datastart="2007-09-22 5:24";
//var dataend="2007-11-12 1:24";
var date1=null;
var date2=new Date();
function Swith(strdate){
var strYear=strdate.substring(0,4);
var strMonth=strdate.substring(5,7);
var strDay=strdate.substring(8,10);
var strHours=strdate.substring(11,13);
var strMinutes=strdate.substring(14,17);
return new Date(strYear,strMonth,strDay,strHours,strMinutes);
}
function GetTime(dateM,datetype){
var s; // sheng ming bian liang
var MinMilli = 1000 * 60; // chu shi hua bian liang
var HrMilli = MinMilli * 60;
var DyMilli = HrMilli * 24;
s="";
if (datetype=="d"){
s +=Math.round(Math.abs(dateM/DyMilli));//+"天";
}else if (datetype=="h"){
s +=Math.round(Math.abs(dateM/HrMilli));//+"小時"
}else if (datetype=="m"){
s +=Math.round(Math.abs(dateM/MinMilli));//+"分";
} else{
s +=Math.round(Math.abs(dateM/1000));//+"秒"
}
return(s); //fan hui jie guo
}
return GetTime((Date.parse(Swith(datastart))-Date.parse(Swith(dataend))),"d");
}