Date()对象
用来获取时间的对象
new Date() 获取当前时间
let date = new Date();
console.log(date);//Sat Mar 02 2019 09:38:43 GMT+0800 (中国标准时间)
- 获取详细日期和时间
var date6 = new Date();
//获取年份
console.log(date6.getFullYear());
//获取月
console.log(date6.getMonth()+1);
//获取日
console.log(date6.getDate());
//获取星期
console.log(date6.getDay());
//获取时
console.log(date6.getHours());
//获取分
console.log(date6.getMinutes());
//获取秒
console.log(date6.getSeconds());
//获取毫秒
console.log(date6.getMilliseconds());
new Date().getTime() 获取当前时间数的毫秒数(时间戳)
- 1970年1月1日凌晨8点到现在的时间(中国在东八区,所以从8点开始算)
let date = new Date();
console.log(date.getTime());//1551490841874
//前面添加加号直接转换
let date = +new Date();
console.log(date);//1551490841874
- Date()函数可以传入具体的时间,来获取你想要得到的一个时间。
格式:new Date(year,month,date,hour,miniute,second)
let date = new Date(2019,1,25,13,10);
console.log(date);//Mon Feb 25 2019 13:10:00 GMT+0800 (中国标准时间)
实现倒计时功能
var div = document.querySelector('.test');
//指定日期时间
var ms1 = new Date(2019,1,25,13,10).getTime();
function daojishi(ms,type){
//获取当前时间戳
var curTime = new Date().getTime();
//计算时差
var timeDiff= ms - curTime;
//从毫秒数转为秒数
timeDiff = Math.floor(timeDiff/1000);
//转为天,时,分,秒。
var day = Math.floor(timeDiff/24/60/60);
var hour = Math.floor(timeDiff/60/60%24);
var min = Math.floor(timeDiff/60%60);
var sec = Math.floor(timeDiff%60);
hour = hour>10?hour:"0"+hour;
min = min>10?min:"0"+min;
sec = sec>10?sec:"0"+sec;
if(timeDiff<=0){
hour=0;
day=0;
min=0;
sec=0;
clearInterval(tm);//清除计时器
}
console.log()
if(type=="/"){
return "剩余"+day+'天 '+hour+'/'+min+"/"+sec;
}else if(type==':'){
return "剩余"+day+'天 '+hour+':'+min+":"+sec;
}else if(type=='-'){
return "剩余"+day+'天 ' +hour+'-'+min+"-"+sec;
}
return "剩余"+day+'天 '+hour+'小时'+min+"分钟"+sec+"秒";
}
var tm = setInterval(function(){
var timer = daojishi(ms1,':');
div.innerText= timer;
},1000);
网友评论