javascript如何取得任意两时间的差

<script language="javascript">
str1 = "2005-1-1 0:0:0:0";
str2 = "2002-2-2 1:1:1:1";

document.write(str1 + '与' + str2 + '的时间差为' +DiffLong(str1,str2));

//Get days and other datetime
//diffrence two datetime
// date1 :更早的日期 小的日期
// date2 :后面的日期 大的日期
//  返回两个时间差的天数小时数分数秒数和毫秒数
function DiffLong(datestr1,datestr2)
{
  var date1 = ToDate(datestr1);
  var date2 = ToDate(datestr2);
  var datetimeTemp;
  var isLater = true;
 
  if(date1.getTime() > date2.getTime())
   {
    isLater = false;
    datetimeTemp = date1;
    date1 = date2;
    date2 = datetimeTemp;
   }
     
   difference= date2.getTime() - date1.getTime();
   thisdays = Math.floor(difference /(1000* 60 * 60*24));

   difference = difference - thisdays * (1000*60*60*24);
   thishours = Math.floor(difference/(1000* 60*60));

   difference = difference - thishours * (1000*60*60);
   thisminutes = Math.floor(difference/(1000* 60));
  
    difference = difference - thisminutes * (1000*60);
    thisseconds = Math.floor(difference/1000);

    difference = difference - thisseconds * 1000;
    thismillseconds = difference;

   //document.write(date1 + 'only  ' + thisdays + '  days until '+  date2 +'<P>');
   //document.write(date1 + 'only  ' + thishours + '  hours until '+  date2 +'<P>');
   //document.write(date1 + 'only  ' + thisminutes + '  minutes until '+  date2 +'<P>');
   //document.write(date1 + 'only  ' + thisseconds + '  seconds until '+  date2 +'<P>');
   //document.write(date1 + 'only  ' + thismillseconds + '  millisconds until '+  date2 +'<P>');
      
   var strRet = thisdays + ' Days  ' + thishours + ' hours  ' +thisminutes + ' minutes  ' +  thisseconds + ' seconds ' + thismillseconds + '  milliseconds';

 return strRet;
}

 // Get Date string to date
 // strdate: 2005-01-01 0:0:0:0
 // it maybe easy by match.Regxp
 //将一个标准化的时间字符串转换成为日期内型
function ToDate(strDate)
{
  var thisDate = new Date();
  thisArr = strDate.split(" ",2);
  thisArr1 = thisArr[0].split("-",3);
  thisDate.setYear(thisArr1[0]);
  thisDate.setMonth(thisArr1[1]);
  thisDate.setDate(thisArr1[2]);

  thisArr2 = thisArr[1].split(":",4);
  thisDate.setHours(thisArr2[0]);
  thisDate.setMinutes(thisArr2[1]);
  thisDate.setSeconds(thisArr2[2]);
  thisDate.setMilliseconds(thisArr2[3]);
  return thisDate;
}
</script>
<html>
<head>
 <title>Test JavaScript about diff two datetime </title>
</head>
<body>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值