~~~
<script>
alert(new Date());//当前系统的时间对象
</script>
~~~
***
课堂练习-1:页面显示时间
~~~
<script type="text/javascript">
window.onload = function() {
var oBody = document.body;
setInterval(fnTime, 1000);
fnTime();
function fnTime() {
var myTime = new Date();
// myTime是object类型 下面是num类型
var iYear = myTime.getFullYear();
var iMonth = myTime.getMonth() + 1;
var iDate = myTime.getDate();
var iWeek = myTime.getDay();
var iHours = myTime.getHours();
var iMin = myTime.getMinutes();
var iSec = myTime.getSeconds();
var str = '';
if(iWeek === 0) iWeek = '星期日';
if(iWeek === 1) iWeek = '星期一';
if(iWeek === 2) iWeek = '星期二';
if(iWeek === 3) iWeek = '星期三';
if(iWeek === 4) iWeek = '星期四';
if(iWeek === 5) iWeek = '星期五';
if(iWeek === 6) iWeek = '星期六';
str = iYear + '年' + iMonth + '月' + iDate + '日 ' + iWeek + ' ' + toTwo(iHours) + ':' + toTwo(iMin) + ':' + toTwo(iSec);
oBody.innerHTML = str;
}
function toTwo(n) {
return n < 10 ? '0' + n : '' + n;
}
}
</script>
~~~
课堂练习-2:图片时间
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function () {
var oBody = document.body;
var oP = document.getElementById('time');
var aImg = document.getElementsByTagName('img');
setInterval(fnTime,1000);
fnTime();
function fnTime() {
var myTime = new Date();
// myTime是object类型 下面是num类型
var iHours = myTime.getHours();
var iMin = myTime.getMinutes();
var iSec = myTime.getSeconds();
var str = toTwo(iHours)+':'+toTwo(iMin)+':'+toTwo(iSec);
oP.innerHTML = str;
for(var i = 0;i < aImg.length;i++){
if(i == 2 || i == 5){
aImg[i].src='img/colon.JPG'
}else{
aImg[i].src='img/'+str.charAt(i)+'.JPG'
}
}
}
function toTwo(n) {
return n < 10 ? '0'+n:''+n;
}
}
</script>
</head>
<body>
<p id="time" style="font-size: 50px;"></p>
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
<img src="img/0.JPG">
</body>
</html>
~~~
课堂练习-3:倒计时
~~~
<script type="text/javascript">
window.onload = function () {
// 现在的时间点(变化的)
// 未来的时间点(不变的)
var iNow = new Date();
var iNew = new Date(2018,8,18,19,54,0);//月份从0开始
//不除1000是毫秒数,Math.floor向下取整,去掉小数点
var t = Math.floor((iNew - iNow)/1000);
var str = Math.floor(t/86400)+'天'+Math.floor(t%86400/3600)+'时'+Math.floor(t%86400%3600/60)+'分'+Math.floor(t%60)+'秒';
/*
* 天:Math.floor(t/86400)
* 时:Math.floor(t%86400/3600)
* 分:Math.floor(t%86400%3600/60)
* 秒:Math.floor(t%60)
*
* 数值:new Date(2017,8,18,19,54,0)
* 字符串:new Date('November 10,2017 22:3:0')
*/
alert(str);
}
</script>
~~~
课堂练习-4:倒计时(要求到0时不变成负数)
***
### 时间戳getTime()
~~~
<script>
alert(new Date().getTime());//得到1970年1月1日到目前为止经过多少毫秒
</script>
~~~
***
拓展练习:
![](https://box.kancloud.cn/574fe1b90c8d5bafc4aa6f42d3adfaf4_664x619.gif)
***
[图片素材下载](https://pan.baidu.com/s/11Luvx0SiX71Zk01lpSUS_g)