Date对象基于1970年1月1日(世界标准时间)
1、无参数
Date()返回当前日期时间
2、带参数
(1)数字型
Date(2022,1,1)返回的月份会+1,因为月份是0-11
(2)字符串型
Date(‘2022-1-1 12:0:0’)
3、日期
返回年:date.getFullYear()
返回月:date.getMonth()+1 //返回月份+1
返回日:date.getDate()
返回星期:date.getDay() //周日返回0
4、星期
var arr=['星期天','星期一','星期二','星期三','星期四','星期五','星期六']
var day=date.getDay()
arr[day]
5、时间
var date=new Date()
返回小时:date.getHours()
返回分钟:date.getMinutes()
返回秒:date.getSeconds()
封装函数返回当前时间
function getTime(){
var time=new Date();
var h=time.getHours();
h=h<10?'0'+h:h;
var m=time.getMinutes();
m=m<10?'0'+m:m;
var s=time.getSeconds();
s=s<10?'0'+s:s;
return h+':'+m+':'+s;
}
6、毫秒(时间戳)
获得Date总毫秒不是当前时间的毫秒,是距离1970年1月1日过了多少毫秒。
var date=new Date()
date.valueOf()
date.getTime()
常用写法:+new Date()
H5新增方法:Date.now()
7、倒计时
输入的时间-现在的时间=剩余的时间
不能使用时分秒进行相减,结果会为负数。
使用时间戳进行计算,最后将剩余的毫秒转换为时分秒。
总秒数:毫秒/1000
计算天:d=parseInt(总秒数/60/60/24)
计算小时:h=parseInt(总秒数/60/60%24)
计算分钟:m=parseInt(总秒数/60%60)
计算秒:s=parseInt(总秒数%60)
计算剩余时间
function countDown(time){
var nowTime= +new Date();
var inputTime= +new Date(time);
var times=(inputTime-nowTime)/1000;
var d=parseInt(times/60/60/24);
var h=parseInt(times/60/60%24);
var m=parseInt(times/60%60);
var s=parseInt(times%60);
return d+'天'+h+'时'+m+'分'+s+'秒';
}