效果图:
代码截图:(关键部分用框框标出)
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span id="date"></span><br>
<span id="week"></span>
</div>
<script>
var showDate = document.getElementById('date') // 获取页面元素
var showWeek = document.getElementById('week') // 获取页面元素
var time = new Date()
var year = time.getFullYear() //获取年份
var month = correctDate(time.getMonth() + 1) //获取月份
var day = correctDate(time.getDate()) //获取日期
var date = "今天是" + year + "年" + month + "月" + day + "日"
var week = time.getDay() // 获取星期几,返回的是0/1/2/3/4/5/6 0代表周日
var weeks = [ "星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
var toWeek = weeks[week] // 获取今日星期
showDate.innerHTML = date // 将日期显示在页面
showWeek.innerHTML = toWeek // 将星期显示在页面
/* 这是一个规范数字的函数:
当时间小于10时,在数字前面加上0,统一都是用两个数字表示,
比如3月5日就显示03月05日
*/
function correctDate(date){
if(date<10){
return '0'+date
}
return date
}
</script>
</body>
</html>
时间js代码:Clock.js文件function Clock() {
var date = new Date()
this.year = date.getFullYear()
this.month = date.getMonth() + 1
this.date = date.getDate()
this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()]
this.hour = date.getHours() <10 ? "0" + date.getHours() : date.getHours()
this.minute = date.getMinutes() <10 ? "0" + date.getMinutes() : date.getMinutes()
this.second = date.getSeconds() <10 ? "0" + date.getSeconds() : date.getSeconds()
this.toString = function() {
return this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day
}
this.toSimpleDate = function() {
return this.year + "-" + this.month + "-" + this.date
}
this.toDetailDate = function() {
return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second
}
this.display = function(ele) {
var clock = new Clock()
ele.innerHTML = clock.toString()
window.setTimeout(function() {clock.display(ele)}, 1000)
}
}
需要显示时间的页面
<SCRIPT src="js/Clock.js" type=text/javascript></SCRIPT> //引入Clock.js文件,注意路径
<label id=clock></label> //放入标签,插入时间
<SCRIPT type=text/javascript> //实例化clock对象
var clock = new Clock()
clock.display(document.getElementById("clock"))
</SCRIPT>