一、常用
var d = new Date()
/* 年,月,日 */
var year = d.getFullYear()
var month = d.getMonth()+1 // 月份是从0开始的,要加1
var date = d.getDate()
/* 时,分,秒 */
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var mills = d.getTime(); //毫秒 1s = 1000毫秒
console.log(d);
console.log(year);
console.log(month);
console.log(date);
console.log(hour);
console.log(minute);
console.log(second);
例1:时间戳
<p id="app"></p>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value
}
return "" + value
}
function showTime() {
var app = document.getElementById("app")
var endTime = "2020-12-01 16:50:00";
// 转换成毫秒
endTime = new Date(endTime).getTime(endTime)
var nowTime = new Date().getTime()
// 获取时间差
var gapTime = endTime - nowTime;
console.log(gapTime)
// 获取小时
var hourse = handleTime(Math.floor(gapTime / 3600000));
console.log(hourse)
// 获取分钟
var minu = handleTime(Math.floor(gapTime / 60000 % 60))
console.log(minu)
// 获取秒
var seconds = handleTime(Math.floor(gapTime / 1000 % 60))
console.log(seconds)
var sum = hourse + ":" + minu + ":" + seconds;
console.log(sum)
// 将时间传入p标签内
app.innerHTML = sum;
//间歇调用 递归
setTimeout(function () {
showTime()
}, 1000)
}
showTime();
</script>
例2:时间图
<div id="app">
<img src="./images/0.png" alt="">
<img src="./images/0.png" alt="">
<span>:</span>
<img src="./images/0.png" alt="">
<img src="./images/9.png" alt="">
<span>:</span>
<img src="./images/8.png" alt="">
<img src="./images/7.png" alt="">
</div>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value
}
return "" + value
}
function showTime() {
var app = document.getElementById("app")
var imgs=document.getElementsByTagName("img")
var d = new Date();
var hour = d.getHours(); // 小时
var minutes =d.getMinutes(); // 分
var second =d.getSeconds(); // 秒
var sum =handleTime(hour) +handleTime(minutes)+handleTime(second)
console.log(sum)
for(var i=0;i<imgs.length;i++){
imgs[i].src="./images/"+sum[i]+".png"
}
//间歇调用 递归
setTimeout(function () {
showTime()
}, 1000)
}
showTime();
console.log(imgs.length)
</script>