Date日期型对象?
<script>
var date=new Date(); //date为由构造函数Date创造出来的日期型对象
console.log(date); //输出为Web Feb 27 2020 23:30:21 GMT+0000(中国标准时间)
console.log(date.getFullYear()); //年
console.log(date.getMonth()); //月份显示是从0开始计算,1就是2月
console.log(date.getDate()); //几号
console.log(date.getDay()); //星期几,0-6 0是星期日
console.log(date.getHours()); //小时
console.log(date.getMinutes()); //分钟
console.log(date.getSeconds()); //秒
console.log(date.getMilliseconds()); //毫秒
//相对来说,有get获取就有set设置
date.setMonth(12); //注意:如果设置12大于11,系统就会自动进1年,并且当前为1月
console.log(date.getDate());
//在一个div里显示日期
var div=document.getElementById("box");
setInterval(Animation,1000);
function Animation(){
var date=new Date();
div.innerHTML=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日 星期"+
(date.getDay()===0?"日":date.getDay())+" "+date.getHours()+"小时"+date.getMinutes()+"分"+date.getSeconds()+"秒";
}
</script>
setInterval(); 指每隔多少毫秒执行一次函数。因此它有两个参数,第一个参数为每次执行的函数,第二个参数为毫秒。如setInterval( fn, 16 );
返回值为id(id是系统给的一个固定值,id的存在是为了使用clearInterval(id);来清掉/停止setInterval()的执行,这样就停止了这个时间间隔)
clearInterval( id ); 清除时间间隔执行函数
setTimeout( 函数, 时间毫秒); 延迟执行函数。有三参数,第一个为需要以后执行的函数,第二个为需要多少毫秒以后,第三个参数略往后再讲。返回值为id同样用来清除该延迟,为clearTime(id); 注意:只要使用setTimeout就一定要在函数中使用clearTimeout清除它,否则会一直存在,占用内存。
练习:电子时钟
时间戳?
var date=new Date(); date.getTime();
而date.getTime();就是时间戳,指1970.1.1 0:0:0到现在的毫秒数
分解代码运行效率,获取代码之间的时间差:
<script>
var time=new Date().getTime();
for(var i=0;i<10000000;i++){ }
console.log(new Date().getTime()-time);
</script>
时间戳作用:
因为每次访问服务器的时间不同,因此,我们可以通过把这个时间戳增加在要访问的地址后面,这样在下次访问的时候就不会读取缓存的数据了。如:
var url="http://www.163.com/index.html?a=1&b=2&time="+new Date().getTime();
location.search 为获取当前地址栏问号后面的字符串.