计算两个时间的时间差(天、小时、分钟、秒数)

例子:计算某个时间距离当前时间相差的天数

1、获取当前时间

Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //
            "H+": this.getHours(), //小时 
            "m+": this.getMinutes(), //
            "s+": this.getSeconds(), //
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
}
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");  //获取当前时间

2、计算两个时间相差(天、小时、分钟、秒数)的函数

function GetDateDiff(startTime,endTime,diffType){
      startTime=startTime.replace(/\-/g,"/");
      endTime=endTime.replace(/\-/g,"/");
      diffType=diffType.toLowerCase();
      var sTime = new Date(startTime);    //开始时间
      var eTime = new Date(endTime);  //结束时间</font>
      //作为除数的数字
      var divNum = 1;
      switch (diffType){
        case "second":
          divNum=1000;
          break;
        case "minute":
          divNum=1000*60;
            break;
        case "hour":
          divNum=1000*3600;
          break;
        case "day":
          divNum=1000*3600*24;
          break;
        default:
          break;
      }
      return parseInt((eTime.getTime()-sTime.getTime())/parseInt(divNum));
}

3、调用函数 计算相差天数

var ti = GetDateDiff('2019-10-09 19:00:00','2019-12-12 14:33:30','day');  //获取两个时间相差天数

猜你喜欢

转载自www.cnblogs.com/dxt510/p/12029028.html