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>
呼叫此方法的範例如下:
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>
相关文章推荐
- Javascript时间差计算函数
- JavaScript计算消息推送时间差
- MySql计算两个日期的时间差函数
- MySql计算两个日期的时间差函数
- Javascript计算时间差函数
- Javascript--普通函数调用-涨工资计算函数
- MySql计算两个日期的时间差函数TIMESTAMPDIFF用法:
- JavaScript如何计算两个日期间的时间差
- javascript Math.pow 函数 详解 【附】年均增长率计算
- JavaScript 计算 目标时间 与 当前时间 的 时间差
- javascript中对数值计算控制精度的函数
- JavaScript如何计算两个日期间的时间差
- java通过javascript引擎调用javascript数学函数实现计算
- 一个日期的扩展函数库包括计算周次和本周时间范围(javascript)
- Javascript 字符串字节长度计算函数代码与效率分析(for VS 正则)
- javascript计算两个日期差的函数代码
- Javascript运用函数计算正方形的面积
- Javascript计算时间差的函数分享
- mysql中计算两个日期的时间差函数TIMESTAMPDIFF用法
- Javascript 时间计算函数