JavaScript基础学习(5)

日期对象、时钟倒计时

时间对象实例
获取时间对象:new Date()
getFullYear()
getMonth() //从0开始计数
getDate()
getDay() //星期
getHours()
getMinutes()
getSecends()
实例:网站电子时钟

练习:图片时钟扩展版 上下切换

倒计时
Date对象参数
数字形式:new Date(2018,9,12,17,01,35); //需要注意月份是从0开始的
字符串形式:new Date('September 12,2018 17:01:35');
月份取值
January、February、March、April、May、June、July、August、September、October、November、December;
时间转换公式
天:Math.floor(t/86400)
时:Math.floor(t%86400/3600)
分:Math.floor(t%86400%3600/60)
秒:t%60
时间戳:getTime()
返回从1970年1月1日0点0分0秒0毫秒
//时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
倒计时原理
现在的时间点(变)
未来的时间点(不变)

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
距离:<input type="text">
<br>
还剩:<input type="text">
<input type="button" value="点击">
<script>
window.onload = function(){
var aInp = document.getElementsByTagName('input');
var iNow = null;
var iNew = null;
var t = 0;
var str = '';
var timer = null;

aInp[2].onclick = function(){
iNew = new Date(aInp[0].value);
clearInterval(timer);

setInterval(function(){
iNow = new Date();
t = Math.floor((iNew - iNow)/1000); //单位:毫秒 -> 秒
if(t >= 0){
str = Math.floor(t/86400) + '天' + Math.floor(t%86400/3600) + '时' + Math.floor(t%86400%3600/60) + '分' + t%60 + '秒';
}, 1000);
aInp[1].value = str;
}else{
clearInterval(timer);
}
};
};
</script>

时间戳
new Date().getTime();
一般用来检测性能,看一段程序运行花费的时间或者用来判断cookie值等

练习:抢购商品练习(倒计时结束后下架商品抖动一下掉落并自动计算价格)
【示例:点击查看