1. new Date()
不设参数,则获取当前时间; 设参数,则获取参数内时间
要创建日期对象,就使用 new 操作符来调用 Date 构造函数:
let now = new Date();
2. 年,月,日,时,分,秒,毫秒
获取当前时间的年,月,日,时,分,秒,毫秒
<!-- 获取当前的时间 -->
<script>
// Date
var d = new Date();
/* 年,月,日 */
var year = d.getFullYear();
var month = d.getMonth();
var date = d.getDate();
/* 时,分,秒,毫秒
1s =1000 millisecond
*/
var hour = d.getHours();
var minute = d.getMinutes()
var second = d.getSeconds();
var mills = d.getTime();
console.log(d);//Tue Dec 01 2020 22:05:23 GMT+0800 (中国标准时间)
console.log(year);
console.log(month+1) //月份是从0开始的,要加1
console.log(date)
console.log(hour)
console.log(minute)
console.log(second);
console.log(mills)
</script>
3. 倒计时时钟
<p id="app">
10:10:01
</p>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value;
}
return value;
}
function showTime() {
var app = document.getElementById("app")
var endTime = "2020-12-02 00:00:00";
/* 1.获取结束时间的毫秒 */;
endTime = new Date(endTime).getTime();
/* 2.获取当前时间的毫秒 */
var nowTime = new Date().getTime();
/* 3.获取他们之间的差 */
var gapTime = endTime - nowTime;
/* 4.将他们的差转换为时分秒 */
var seconds = Math.floor(gapTime / 1000);
var hours = handleTime(Math.floor(seconds / 3600));
seconds = seconds % 3600;
var minutes = handleTime(Math.floor(seconds / 60));
seconds = handleTime(seconds % 60);
var sum = hours + ":" + minutes + ":" + seconds;
app.innerHTML = sum;
setTimeout(function(){
showTime()
},1000)
}
showTime();
</script>
或者
showTime();
setInterval(function(){
showTime();
},1000)
4.动态时钟
<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/0.png" alt="">
<span>:</span>
<img src="images/0.png" alt="">
<img src="images/0.png" alt="">
</div>
<script>
function handleTime(value) {
if (value < 10) {
return "0" + value;
}
return ""+ value;
}
function showTime() {
var imgs = document.querySelectorAll("#app img")
var d = new Date();
var hours = handleTime(d.getHours());
var minutes = handleTime(d.getMinutes());
var seconds = handleTime(d.getSeconds());
var sum = hours + minutes + seconds;
console.log(sum);
for (var i = 0; i < imgs.length; i++) {
console.log(sum[i])
// imgs[i].src = "images/" + sum[i] + ".png";
imgs[i].src = `images/${sum[i]}.png`;
}
setTimeout(function(){
showTime()
},1000)
}
showTime()
</script>