1、思路:输入的时间减去现在的时间就是剩余的时间,也即是倒计时,但不能直接用时间相减。
可使用时间戳==》用户输入时间总的毫秒数减去现在时间的总毫秒数,得到的就是剩余时间
最后再将剩余时间总的毫秒数转换成天、时、分、秒
【转换公式】
d=parseInt(总秒数/60/60/24) 计算天数
h=parseInt(总秒数/60/60%24) 计算小时
m=parseInt(总秒数/60%60) 计算分钟数
s=parseInt(总秒数%60) 计算秒数
function countTime(time) {
//获取当前时间总的毫秒数
var nowTime = +new Date();
//获取用户输入时间总毫秒数
var inputTime = +new Date(time);
//获取两者之间相差的秒数
var times = (inputTime - nowTime) / 1000;
var d = parseInt(times / 60 / 60 / 24); //天
d = d < 10 ? "0" + d : d;//当数值小于10的时候,在前面加0
var h = parseInt((times / 60 / 60) % 24); //时
h = h < 10 ? "0" + h : h;//同上
var m = parseInt((times / 60) % 60); //分
m = m < 10 ? "0" + m : m;//同上
var s = parseInt(times % 60); //秒
s = s < 10 ? "0" + s : s;//同上
return d + "天" + h + "时" + m + "分" + s + "秒";
}
console.log(countTime("2022 /3 / 22 16:10:00"));
2、获取倒计时
思路:同上,在此增加了两种小的知识点
获取事件戳的方法:可用构造函数
拼接字符串的方法:拼字符串***** `` 可以 使用 ${变量} --这个整体 最后执行的时候 会被解析变量的值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="box"></div>
<script>
var tDate = new Date("2022-03-25 18:00:00");
setInterval(function() {
let now = new Date();
//获取两个时间戳的差(毫秒)
// (方法1)var temp=tDate-now;
//(方法2)var temp = tDate.getTime() - now.getTime();
// (方法3)Date.now() 静态方法--构造函数直接使用的方法 --- 获取当前时间戳
var temp = tDate.getTime() - Date.now();
var totalSeconds = parseInt(temp / 1000); //总的秒数
var sec = totalSeconds % 60; //封60进位余多少秒
var totalMins = parseInt(temp / 1000 / 60); //总的分钟数
var mins = totalMins % 60; //封60进位余多少分钟
var totalHours = parseInt(temp / 1000 / 60 / 60); //总的小时数
//数字小于10时在前面补0,效果好看
if (sec < 10) sec = "0" + sec;
if (mins < 10) sec = "0" + mins;
if (totalHours < 10) totalHours = "0" + totalHours;
//字符串拼接方法1
var str = totalHours + ":" + mins + ":" + sec;
console.log(str);
//字符串拼接方法2(好用)
var str2 = `离下课还有 ${totalHours} 小时 ${mins}分钟 ${sec}秒`;
box.innerHTML = str2;
}, 1000);
</script>
</body>
</html>