已知数据
当前时间:new Date();
过去时间:alarmTime = “2021-02-23 13:55:18”;
功能点
使用getTime() 得到指定日期之间的毫秒数;
代码段
当前时间毫秒数 let timestamp = new Date().getTime();
过去时间毫秒数 let oldTime = new Date(item.alarmTime).getTime();
let total = (timestamp - oldTime) / 1000;
let day = parseInt(total / (24 * 60 * 60)); //计算整数天数
let afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
let hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
let afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数
let min = parseInt(afterHour / 60); //计算整数分
let afterMin = parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); //取得算出分后剩余的秒数
let time = day + "天 " + hour + " 小时 " + min + " 分钟 " + afterMin + " 秒";
完整代码
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>获取倒计时间</title>
</head>
<body>
<h3>时间已过期:<span id="time"></span></h3>
</body>
<script type="text/javascript">
window.onload = function(){
duractionTime();
}
function duractionTime(){
setInterval(function(){
let timestamp = new Date().getTime();
let data = '2021-02-23 13:55:08';
let oldTime = new Date(data).getTime();
let total = (timestamp - oldTime) / 1000;
let day = parseInt(total / (24 * 60 * 60)); //计算整数天数
let afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
let hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
let afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数
let min = parseInt(afterHour / 60)<10?'0'+parseInt(afterHour / 60):parseInt(afterHour / 60); //计算整数分
let afterMin = parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60) < 10?'0'+parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60):parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60) //取得算出分后剩余的秒数
let time = day + "天 " + hour + " 小时 " + min + " 分钟 " + afterMin + " 秒";
document.getElementById('time').innerHTML = time;
},1000)
}
</script>
</html>