js计算两个日期相差的天数

JavaScript019

js计算两个日期相差的天数,第1张

这边写了代码,请保存为.html文件后测试

<html>

<body>

选择开始日期: <input type="date" id="start_date" />

选择结束日期: <input type="date" id="end_date" />

<hr/>

<button type="submit" onclick="end_date=new Date(document.getElementById('end_date').value)

start_date=new Date(document.getElementById('start_date').value)

document.getElementById('showhowmanyday').innerText=(end_date.getTime()-start_date.getTime())/(24*3600*1000)">计算两个日期相差的天数</button>

<h1 id="showhowmanyday"/>

</body>

</html>

<SCRIPT LANGUAGE="JavaScript">

<!--

function deal(){

//var Y = 6

//var R ="2009-11-01"

var R = document.getElementById('date').value +''

var Y = document.getElementById('month').value

alert(R)

var year=R.substr(0,4)

var month=R.substr(5,2)

var day=R.substr(8,2)

if((parseInt(month)+parseInt(Y)) >12){

year++

month = parseInt(month) + parseInt(Y) - 12

}else{

month = parseInt(month) + parseInt(Y)

}

alert(year+"-"+month+"-"+day)

R = new Date(year,month,day,00,00,00)

dateNow = new Date()

var diff = R.getTime() - dateNow.getTime()

var days = Math.floor(diff/(1000*60*60*24))

var str = "与今天相差" + days + "天"

if(R >dateNow){

alert("大于今天!"+"\n"+str)

}else{

alert("小于今天!"+"\n"+str)

}

}

//-->

</SCRIPT>

月<input type="text" id="month" value="6">

日期 <input type="text" id="date" value="2009-11-01">

<input type="button" value="submit" onClick="deal()">

这样的吗