时间对象是构造函数所以要new
var date= new Date ( )
console. log ( date)
var date1= new Date ( 2020 , 12 , 26 )
var date2= new Date ( '2020-12-26 20:20:22' )
console. log ( date1)
console. log ( date2)
格式化年月日 星期
var date= new Date ( )
var year= date. getFullYear ( )
var month= date. getMonth ( )
var dates= date. getDate ( )
var day= date. getDay ( )
var days= [ '星期日' , '星期一' , '星期二' , '星期三' , '星期四' , '星期五' , '星期六' ]
console. log ( year+ '年' + month+ '月' + dates+ '日 ' + days[ day] ) * /
格式化时间
function getTimer ( ) {
var time= new Date ( )
var h= time. getHours ( )
h = h> 10 ? h : '0' + h
var m= time. getMinutes ( )
m = m> 10 ? m : '0' + m
var s= time. getSeconds ( )
s = s> 10 ? s : '0' + s
return h+ ':' + m+ ':' + s
}
console. log ( getTimer ( ) ) * /
获取时间戳3种方式
var time= new Date ( )
console. log ( time. valueOf ( ) )
console. log ( time. getTime ( ) )
console. log ( + new Date ( ) )
console. log ( Date. now ( ) )
倒计时
function countDown ( time) {
var now= + new Date ( )
var input= + new Date ( time)
var times= ( input- now) / 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 )
h= h < 10 ? '0' + h : h
m= m < 10 ? '0' + m : m
s= s < 10 ? '0' + s : s
return '还剩:' + d+ '天' + h+ '时' + m+ '分' + s+ '秒'
}
console. log ( countDown ( '2021-1-1 8:8:8' ) )