layui/laydate计算两个日期之间天数
html
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">日期范围</label>
<div class="layui-inline" id="dateRank">
<div class="layui-input-inline">
<input type="text" lay-verify="required" autocomplete="off" name="start_time" id="start_time" class="layui-input" placeholder="开始日期">
</div>
<div class="layui-form-mid">-</div>
<div class="layui-input-inline">
<input type="text" lay-verify="required" autocomplete="off" name="end_time" id="end_time" class="layui-input" placeholder="截止日期">
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label layui-require">天数</label>
<div class="layui-input-inline">
<input name="days" lay-verify="required" class="layui-input" autocomplete="off" id="days" placeholder="请选择开始与截止日期">
</div>
<div class="layui-input-inline" style="width: 100px;">
<input type="button" value="计算天数" onclick="check()" class="layui-btn">
</div>
</div>
</div>
js
<script>
layui.use(['layer','laydate','form'],function(){
let form = layui.form;
let $ = layui.jquery;
let layer = layui.layer;
let laydate=layui.laydate;
//选择开始时间
laydate.render({
elem: '#dateRank',
range: ['#start_time', '#end_time'],
});
});
//计算日期
function check(){
let start=document.getElementById("start_time").value;//获取起始日期
let end=document.getElementById("end_time").value;//获取结束日期
if(start === ""){
layer.msg("请选择开始日期!", {icon:2,time:1500});
}
else if(end === ""){
layer.msg("请选择截止日期!", {icon:2,time:1500});
}
document.getElementById("days").value=getDays(start, end);
}
//返回计算天数值
function getDays(startDate,endDate){
let date1Str = startDate.split("-");//将日期字符串分隔为数组,数组元素分别为年、月、日
//根据年、月、日的值创建Date对象
let date1Obj = new Date(date1Str[0],(date1Str[1]-1),date1Str[2]);
let date2Str = endDate.split("-");
let date2Obj = new Date(date2Str[0],(date2Str[1]-1),date2Str[2]);
let t1 = date1Obj.getTime();//返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
let t2 = date2Obj.getTime();//返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
let datetime = 1000*60*60*24; //一天时间的毫秒值
let minusDays = Math.floor(((t2-t1)/datetime));//计算出两个日期天数差
let days = Math.abs(minusDays);//如果结果为负数,取绝对值
//console.log(days);
if(!days) { //在没有选择开始或结束日期时返回"NaN"类型,所以做此判断
return '';
}
return days + 1;
}
</script>
写在后面:
本文内容主要是参考/拷贝互联网稍加改动,具体网址不记得了,若有冒犯,请联系我删除。13073932#163.com