1、新建一个index.html并添加一个用于显示时间的标签
index.html
<!DOCTYPE html><html><head><title>使用JavaScript实现动态显示当前日期和时间</title></head><body>当前时间:<p id="datetime"></p></body></html>
2、在同一html文件中添加JavaScript代码实现时间更新
index.html
<script>//获取当前日期和时间function updateClock() {var now = new Date();var date = now.toLocaleDateString();var hours = now.getHours();var minutes = now.getMinutes();var seconds = now.getSeconds();hours = checkTime(hours);minutes = checkTime(minutes);seconds = checkTime(seconds);document.getElementById('datetime').innerHTML = date + "\t" + hours + ":" + minutes + ":" + seconds;}// 在数字前面补0function checkTime(i) {if (i < 10) {i = "0" + i} return i;}setInterval(updateClock, 1000); // 每秒更新一次</script>
完整代码
index.html
<!DOCTYPE html><html><head><title>使用JavaScript实现动态显示当前日期和时间</title></head><body>当前时间:<p id="datetime"></p><script>//获取当前日期和时间function updateClock() {var now = new Date();var date = now.toLocaleDateString();var hours = now.getHours();var minutes = now.getMinutes();var seconds = now.getSeconds();hours = checkTime(hours);minutes = checkTime(minutes);seconds = checkTime(seconds);document.getElementById('datetime').innerHTML = date + "\t" + hours + ":" + minutes + ":" + seconds;}// 在数字前面补0function checkTime(i) {if (i < 10) {i = "0" + i} return i;}setInterval(updateClock, 1000); // 每秒更新一次</script></body></html>