layui时间插件实现动态限制可选时间范围和统计时间间隔

<script>
layui.use('laydate', function() {
  var laydate = layui.laydate;
  var start = laydate.render({ //开始时间
    elem: '#startDate',
    type: 'datetime',
    format: 'yyyy-MM-dd HH:mm:ss',
    done: function(value, date) { //点击确定回调事件
      endMax = end.config.max;
      end.config.min = date;
      end.config.min.month = date.month - 1;
      timeOperation(value, $("#endDate").val())
    },
    change: function(value, date, endDate) { //点击改变回调事件
      var timestamp2 = Date.parse(new Date(value));
      timestamp2 = timestamp2 / 1000;
      end.config.min = timestamp2;
      end.config.min.month = date.month - 1;
    }
  });
  var end = laydate.render({ //结束时间
    elem: '#endDate',
    type: 'datetime',
    format: 'yyyy-MM-dd HH:mm:ss',
    done: function(value, date) { //点击确定回调事件
      if ($.trim(value) == '') {
        var curDate = new Date();
        date = {
          'date': curDate.getDate(),
          'month': curDate.getMonth() + 1,
          'year': curDate.getFullYear()
        };
      }
      start.config.max = date;
      start.config.max.month = date.month - 1;
      timeOperation($("#startDate").val(), value)
    }
  });
});

//统计时间间隔
function timeOperation(startTimeStr, endTimeStr) {
  if (startTimeStr != "" && startTimeStr != null && endTimeStr != "" && endTimeStr != null) {
    //开始时间
    var startDate = new Date(startTimeStr.replace("-", "/").replace("-", "/"));
    //结束时间
    var endDate = new Date(endTimeStr.replace("-", "/").replace("-", "/"));
    if (endDate < startDate) {
      layer.msg("开始时间不能大于结束时间!")
      return false;
    }
    $("#timeSum").html((endDate.getTime() - startDate.getTime()) / 1000)
    console.log((endDate.getTime() - startDate.getTime()) / 1000 + "秒")
    console.log(parseInt((endDate.getTime() - startDate.getTime()) / 1000 / 60) + "分" + (endDate.getTime() - startDate.getTime()) /
      1000 % 60 + "秒")
    console.log(parseInt((endDate.getTime() - startDate.getTime()) / 1000 / 60 / 60) + "时" +
      parseInt((endDate.getTime() - startDate.getTime()) / 1000 / 60 % 60) + "分" +
      (endDate.getTime() - startDate.getTime()) / 1000 % 60 + "秒")
  }
}
</script>

posted @ 2020-06-10 16:49  析草的残梦  阅读(1927)  评论(0编辑  收藏  举报