HTML代码

1
2
<p id="tipForTime" style="color: #00B0E8;text-align: center"></p>
<p>当前时间:&nbsp;<span id="time" style="color: grey"></span></p>

JavaScript代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//获取当前时间
window.onload = function () {
window.requestAnimationFrame(getDate)
}

function getDate() {
window.setTimeout(function () {
window.requestAnimationFrame(getDate)
}, 1000 / 2)
var d = new Date();
var year = d.getFullYear() //获取年
var month = d.getMonth() + 1; //获取月,从 Date 对象返回月份 (0 ~ 11),故在此处+1
var day = d.getDay() //获取日
var days = d.getDate() //获取日期
var hour = d.getHours() //获取小时
var minute = d.getMinutes() //获取分钟
var second = d.getSeconds() //获取秒

if (month < 10) month = "0" + month
if (days < 10) days = "0" + days
if (hour < 10) hour = "0" + hour
if (minute < 10) minute = "0" + minute
if (second < 10) second = "0" + second
if (hour >= 6 && hour < 12) {
$("#tipForTime").html("早上好!");
} else if (hour >= 12 && hour < 19) {
$("#tipForTime").html("下午好!");
} else if (hour >= 19 && hour < 23) {
$("#tipForTime").html("晚上好!");
} else {
$("#tipForTime").html("夜深了!请注意休息!!!");
}
var week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
var Tools = document.getElementById("time")
var time = year + "-" + month + "-" + days + " " + hour + ":" + minute + ":" + second+" "+week[day]
$("#time").html(time);
}

结果如下图

img

PS.

来源:HTML+JS动态获取当前时间_公众号:【C you again】-CSDN博客_js显示当前时间