Date对象
简介
语法
Date 对象由新的 Date() 构造函数创建。
有 4 种方法创建新的日期对象:
- new Date()
- new Date(year, month, day, hours, minutes, seconds, milliseconds)
- new Date(milliseconds)
- new Date(date string)
倒计时效果
<!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>
<script>
// 倒计时效果
// 1.核心算法:输入的时间减去现在的时间就是剩余的时间,即倒计时,但是不能用时分秒相减,比如05分减去25分,结果会出现负数。
// 2.用时间戳来做。用户输入时间总的毫秒数减去现在时间总的毫秒数,得到的就是剩余时间的毫秒数。
// 3.把剩余时间总的毫秒数转换为天、时、分、秒
// 转换格式:
// d = parseInt(总秒数 / 60 / 60 / 24); 计算天数
// h = parseInt(总秒数 / 60 / 60 % 24); 计算小时
// m = parseInt(总秒数 / 60 % 60); 计算分钟
// s = parseInt(总秒数 % 60); 计算秒数
function countDown(time) {
var nowDate = +new Date(); // 返回当前时间总毫秒数
var inputDate = +new Date(time); // 返回用户输入时间总毫秒数
var times = (inputDate - nowDate) / 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 + '秒'
}
var date = new Date();
console.log(date);
console.log(countDown('2022-4-1 00:00:00'));
</script>
</head>
<body>
</body>
</html>