内置日期对象 Date
1.声名-使用
var date = new Date();
console.log( date ); // Thu Feb 13 2020 14:40:17 GMT+0800 (中国标准时间)
// getDate() 获取日 1-31
// getDay() 获取星期 0-6
// getMonth() 获取月 0-11
// getFullYear() 获取完整年份
// getHours() 获取小时 0-23
// getMinutes() 获取分钟 0-59
// getSeconds() 获取秒钟 0-59
// getMilliseconds() 获取毫秒 1s = 1000ms
// getTime() 返回累计毫秒数(1970/1/1午夜) 时间戳
var date = new Date('2100/01/01 24:00:00'); // 定义将来的时间 // 以前的时间也能定义
2.日历案列
window.onload = function () {
var date = new Date();
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var week = date.getDay();
var weeks = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六',];
var top = document.getElementById("box_top");
var bt = document.getElementById("box_bt");
top.innerText = y + '年' + m +'月'+ d + '日' + weeks[week];
bt.innerText = d;
}
3.定时器 setInterval
//第一种写法
window.setInterval("alert('1')",1000); // 在 js 中定时器需要使用毫秒
// 第二种写法
setInterval(function(){
alert('1');
}, 1000);
// 第三种写法
function test(){
alert('1');
}
setInterval( test , 1000 );
4.设置定时器,和结束定时器
var time = null;
// 设置定时器
time = setInterval(function(){
console.log('1');
},1000);
// 结束定时器
clearInterval( time );
5.时间戳计算
// 天
var d = parseInt( second / 3600 / 24);
// 小时
var h = parseInt( second / 3600 % 24);
// 分钟
var m = parseInt( second / 60 % 60);
// 秒数
var s = second % 60;
6.时钟案列
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
#box{
width: 300px;
height: 300px;
background: url("b.png") no-repeat;
margin: 20px auto;
position: relative;
}
#hour{
background: url("h.png") no-repeat;
width: 33px;
height: 65px;
position: absolute;
top: 92px;
left:44.5%;
}
#min{
background: url("m.png") no-repeat;
width: 10px;
height: 90px;
position: absolute;
top: 65px;
left:50%;
}
#sec{
background: url("s.png") no-repeat;
width: 22px;
height: 120px;
position: absolute;
top: 41px;
left:46.5%;
}
</style>
<div id="box">
<div id="hour"></div>
<div id="min"></div>
<div id="sec"></div>
</div>
window.onload = function () {
var hour = document.getElementById('hour');
var min = document.getElementById('min');
var sec = document.getElementById('sec');
// 定时器
var timer = setInterval(function(){
// 获取当前时间戳
var date = new Date();
// 求出总毫秒数
var allSec = date.getMilliseconds();
var s = date.getSeconds() + allSec / 1000; // 获取秒数
var m = date.getMinutes(); // 获取分钟
var h = date.getHours() % 12; // 获取小时
// 旋转 一小时30度 一分钟6度 一秒钟6度
hour.style.cssText = 'transform: rotate('+ h * 30 +'deg); transform-origin:50% 90%;';
min.style.cssText = 'transform: rotate('+ m * 6 +'deg); transform-origin:40% 95%;';
sec.style.cssText = 'transform: rotate('+ s * 6 +'deg); transform-origin:50% 90%;';
},100)
}
时钟案列效果为
由于指针素材随便扣得 所以位置有点偏差