js计算两个字符串时间的天数差的代码

发布时间:2020-08-23编辑:脚本学堂
本文介绍下,用于计算两个字符串时间的天数差的代码,有需要的朋友,可以参考学习下。

1,求两个字符串时间的天数差

var s = ((new Date(paramObj.end_date.replace(/-/g,"/"))) - (new Date(paramObj.start_date.replace(/-/g,"/"))));
var day = s/1000/60/60/24 

2,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("2013/08/25 07:30:00");
var eDT = new Date("2013/08/25 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>

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

问题1:
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 ;得到毫秒差,换算成小时即可

问题2:
把字符串:"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();