Javascript时间差计算函数代码实例

Javascript时间差计算函数代码实例

<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>

<script>

var s1 = "2009/08/01";

var s2 = "2009/12/31";

s1 = new Date(s1);

s2 = new Date(s2);

var time= s2.getTime()-s1.getTime() ;

var days = parseInt(time / (1000 * 60 * 60 * 24));

alert("相差天数: " + days);

</script>

javascript 计算时间差

<script>

var startDate= new Date("2004/3/1 12:00");

var endDate= new Date("2004/3/1 15:00");

var df=(endDate.getTime()-startDate.getTime())/1000/3600;

alert(df+"小时");

</script>

<SCRIPT LANGUAGE="JavaScript">

<!--

var st1 = "2009/8/25 19:35";

var st2 = "2009/8/25 19:28";

var time1 = new Date(st1);

var tiem2 = new Date(st2);

var days = (time1.getTime()-tiem2.getTime())/1000/60;//分钟

//alert(days);

document.writeln(days);

//-->

</SCRIPT>

求助用javascript求两日期相减所得时间差!

var   oldtime=Date.parse("2005-1-10   8:00:00");

var   newtime=Date.parse("2005-1-11   12:00:00");

var   diff   =   newtime   -   oldtime   ;得到毫秒差,换算成小时就可以了

谁能告诉我怎样把字符串:"2005-1-12   8:00:00"转换成datetime型!

var   str="2005-1-12   8:00:00";

var   arr=str.split("   ");

var   arr1=arr[0].split("-");

var   arr2=arr[1].split(":");

//注意new   Date()中的六个参数分别是   年月日时分秒   其中月份从0开始,

var   date=new   Date(arr1[0],arr1[1],arr1[2],arr2[0],arr2[1],arr2[2]);

//获取现在时间

var now =new Date();

var year = now.getFullYear();

var month = now.getMonth()+1;

var day = now.getDate();

var hour = now.getHours();

var minute = now.getMinutes();

var second = now.getSeconds();

上一篇:VBA里,workbook.path不是全名,而workbook.fullname才是。而file.path就是全名,没有file.fullname


下一篇:kylin(二): Calcite