Posted on 2007-04-21 18:27
玄铁剑 阅读(799)
评论(0) 编辑 收藏 引用 所属分类:
Javascript
計算日期的時間差(DateObject.dateDiff)
擴充方法原始碼如下:
<script language="javascript">
Date.prototype.dateDiff = function(interval,objDate){
//若參數不足或 objDate 不是日期物件則回傳 undefined
if(arguments.length<2||objDate.constructor!=Date) return undefined;
switch (interval) {
//計算秒差
case "s":return parseInt((objDate-this)/1000);
//計算分差
case "n":return parseInt((objDate-this)/60000);
//計算時差
case "h":return parseInt((objDate-this)/3600000);
//計算日差
case "d":return parseInt((objDate-this)/86400000);
//計算週差
case "w":return parseInt((objDate-this)/(86400000*7));
//計算月差
case "m":return (objDate.getMonth()+1)+((objDate.getFullYear()-this.getFullYear())*12)-(this.getMonth()+1);
//計算年差
case "y":return objDate.getFullYear()-this.getFullYear();
//輸入有誤
default:return undefined;
}
}
</script>
呼叫此方法的範例如下:
<script language="javascript">
var sDT = new Date("2000/12/31 08:00:00");
var eDT = new Date();
document.writeln("秒差 : "+sDT.dateDiff("s",eDT)+"<br>");
document.writeln("分差 : "+sDT.dateDiff("n",eDT)+"<br>");
document.writeln("時差 : "+sDT.dateDiff("h",eDT)+"<br>");
document.writeln("日差 : "+sDT.dateDiff("d",eDT)+"<br>");
document.writeln("週差 : "+sDT.dateDiff("w",eDT)+"<br>");
document.writeln("月差 : "+sDT.dateDiff("m",eDT)+"<br>");
document.writeln("年差 : "+sDT.dateDiff("y",eDT)+"<br>");
</script>