您的位置:首页 > Web前端 > JavaScript

Javascript时间差计算函数

2008-05-04 13:58 246 查看
<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("2004/05/20 07:30:00");
var eDT = new Date("2005/05/20 08:32:02");
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: