1.判斷兩個日期的差:
/**計算日期天數差的函數-hanliwei-2013-03-14*/
function DateDiff(sDate1,sDate2) {
//sDate1和sDate2的格式為xxxx-xx-xx
var aDate,oDate1,oDate2,iDays;
//轉換為xx-xx-xxxx格式
aDate = sDate1.split("-");
oDate1 = new Date(aDate[1] + "," + aDate[2] + "," + aDate[0]);
aDate = sDate2.split("-");
oDate2 = new Date(aDate[1] + "," + aDate[2] + "," + aDate[0]);
alert(sDate1 + "=====" + sDate2 + "==" + oDate1 + "===" + oDate2);
alert("--------" + (oDate1 - oDate2));
//把相差的毫秒數轉換為天數
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24 );
return iDays;
}
2.判斷兩個日期的大小:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
<script type="text/javascript">
function checkdate() {
var d1=new Date('1988-1-1 11:11:11'.replace(/\-/g,'/')),
d2=new Date('1988-1-1 11:12:11'.replace(/\-/g,'/'));
alert(d1 + "===============" + d2);
alert(d1<d2) ;
//得到日期值并轉化成日期格式,replace(/\-/g, "\/")是根據驗證表達式把日期轉化成長日期格式,這樣
//再進行判斷就好判斷了
var s1 = document.getElementById("txtstart").value;
var s2 = document.getElementById("txtend").value;
alert(s1);
alert(s2);
var sDate = new Date(s1.replace(/\-/g,'/'));
var eDate = new Date(s2.replace(/\-/g,'/'));
alert(sDate + "=============" + eDate);
if(sDate > eDate)
{
alert("結束日期不能小于開始日期");
//return false;
}
//return true;
}
</script>
</head>
<body>
<input type="button" value="xxx" onclick="checkdate()" />
<input type="text" value="2012-03-13" id="txtstart"/>
<input type="text" value="2012-03-12" id="txtend"/>
</body>
</html>
本文轉自韓立偉 51CTO部落格,原文連結:http://blog.51cto.com/hanchaohan/1154486,如需轉載請自行聯系原作者