在以前写的这篇文章的代码上增加年月日的显示
JavaScript 做一个简单的数字时钟(只有时分秒)_js 只有时分秒的插件-CSDN博客
运行效果
只是把日期和时间显示出来,并没有特别去做美化,所以并不美观
下面是代码:
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background: #333;
}
.clock {
width: 430px;
height: 200px;
background: #000000;
margin: 20px auto;
display: flex;
justify-content: center;
align-items: center;
flex-wrap:wrap;
}
#clockTime{
font-size: 100px;
font-weight: bold;
color: #f7c08a;
}
#clickDate{
font-size: 30px;
color: #ff2d51;
}
</style>
<body>
<div class="clock">
<div id="clockTime"></div>
<div id="clickDate"></div>
</div>
<script>
showDateTime();
//开启一个定时器,让网页上的时间能自动更新
let timer = setInterval(showDateTime,1000);
//搞起
function showDateTime() {
//获取当前日期
let years = new Date().getFullYear();
let months = new Date().getMonth()
let days = new Date().getDate();
// 获取当前时间
let hour = new Date().getHours();
let minute = new Date().getMinutes();
let second = new Date().getSeconds();
//设定一个字符串
let showTime = '';
//把时间按特定格式显示
showTime = hour + ":" + minute + ":" + second;
showDate = years + "年" + months + "月" + days + "日"
//将时间显示到页面
document.getElementById("clockTime").innerHTML=showTime;
document.getElementById("clickDate").innerHTML = showDate
}
</script>
</body>
showDateTime()里的new Date()还可以这么写,例:
let t = new Date();
let years = t.getFullYear();
let months = t.getMonth();
这是把new Date()赋值给变量 t ,然后后面获取时间的时候,就不需要重复写new Date(),而直接写 t ,代码能简洁一些,效果是一样的。