获取当前时间
//北京时间
setInterval(sjc, 1000)
function sjc() {
let h2 = document.querySelector("h2")
let date = new Date();
n = date.getFullYear(); //获取年
y = date.getMonth() + 1; //获取月
r = date.getDate(); //获取日
z = date.getDay(); //获取周
x = date.getHours(); //获取小时
f = date.getMinutes(); //获取分钟
zhou = ["日", "一", "二", "三", "四", "五", "六"]
h2.innerHTML = `现在时间: ${n}年 : ${ fn(y)}月 : ${ fn(r)}日   星期${zhou[z]}    ${x}: ${ fn(f)} `
}
sjc()
function fn(tt) {
return tt < 10 ? "0" + tt : tt
}//补零
获取距离**时间还有多少时间
//活动倒计时
setInterval(ddjs, 1000)
function ddjs() {
let h1 = document.querySelector("h1")
let sj = new Date() * 1 //获取现在时间戳
let sjc = new Date(2021, 11, 11, 00, 00) * 1 //获取活动时间的时间戳
let djs = sjc - sj //剩余时间戳
let t = 24 * 60 * 60 * 1000; //计算天数
let h = 60 * 60 * 1000; //计算小时
let f = 60 * 1000; //计算分钟
let tt = Math.floor(djs / t); //获取剩余天数
let hh = Math.floor(djs % t / h); //获取剩余小时数
let ff = Math.floor(djs % h / f); //获取剩余分钟数
let s = Math.floor(djs % f / 1000); //获取剩余秒数
h1.innerHTML = ` 距离活动: ${fn(tt)}天 : ${fn(hh)}时 : ${fn(ff)}分 : ${fn(s)}秒 `
}
ddjs()
function fn(tt) {
return tt < 10 ? "0" + tt : tt
} //补零
HTML部分
<body>
<h2></h2>
<h1></h1>
</body>
css部分
<style>
h1 {
background-image: url(imges/2.jpg);
width: 55.7143rem;
height: 28.2857rem;
margin: auto;
text-align: center;
line-height: 48rem;
font-size: 50px;
color: rgb(130, 205, 235);
}
h2 {
font-family: lisu;
font-size: 35px;
text-align: center;
}
</style>