先看效果图
开始时间默认为当前时间,结束时间可以选择(默认过年的时间),这里求当前时间到某一段时间段相差多少时间。
话不多说上代码
html代码
<div class="search-package">
<div class="time-package">
<span class="time-span">开始时间</span>
<input type="datetime-local"
disabled
class="date-time"
id="startTime">
</div>
<div class="time-package">
<span class="time-span">结束时间</span>
<input type="datetime-local"
class="date-time"
id="endTime">
</div>
<div id="time"></div>
</div>
css代码
<style>
#time {
width: 300px;
height: 100px;
background-color: rgba(127, 255, 202);
margin: 0 auto 50px;
text-align: center;
line-height: 100px;
border: 1px solid black;
border-radius: 50px;
color: rgb(31, 16, 241);
font-size: 20px;
font-weight: bold;
}
.search-package {
padding: 16px 8px;
text-align: center;
}
.date-time {
width: 198px;
height: 42px;
line-height: 1;
appearance: none;
padding-left: 14px;
font-size: 16px;
color: #525C66;
outline: none;
border-radius: 4%;
}
input[type='datetime-local'] {
position: relative;
}
input[type='datetime-local']::-webkit-calendar-picker-indicator {
position: absolute;
right: 0;
padding-left: calc(100% - 20px);
padding-right: 10px;
}
.time-package {
display: inline-block;
margin: 50px 10px 10px;
border: 1px slateblue solid;
background: #6152661e;
padding: 4px 8px;
border-radius: 2px;
}
.time-span {
color: #1887e2cb;
font-weight: bold;
font-size: 14px;
margin-right: 10px;
}
</style>
js代码
<script>
let timer = document.getElementById('time');
let startTime = document.getElementById('startTime')
let endTime = document.getElementById('endTime')
//设置结束时间默认为过年的时间
endTime.value = '2023-01-22 00:00:00';
setInterval(() => {
//设置开始时间默认为当前时间
startTime.value = getDayTime();
dateTimes();
})
//封装时间的函数
function dateTimes() {
let start = startTime.value
document.getElementById('spanId').innerText = start
let end = endTime.value
//获取当前时间
const today = new Date(start.replace(/-/g, '/').replace('T', ' '));
document.getElementById('spanId2').innerText = today
//获取过年时间
const newYear = new Date(end.replace(/-/g, '/').replace('T', ' '));
//相差时间
let diffTime = newYear.getTime() - today.getTime();
const day = Math.floor(diffTime / (1000 \* 60 \* 60 \* 24))
diffTime = diffTime % (1000 \* 60 \* 60 \* 24)
const hour = Math.floor(diffTime / (1000 \* 60 \* 60))
diffTime = diffTime % (1000 \* 60 \* 60)
const minute = Math.floor(diffTime / (1000 \* 60))
diffTime = diffTime % (1000 \* 60)
const seconds = Math.floor(diffTime / (1000))
let dateStr = `还有 ${day}天 ${hour}时${minute}分${seconds}秒`
timer.innerText = dateStr;
}
//获取当前时间