Web API 中的时间相关属性

237 阅读1分钟

时间对象

获得当前时间

let date = new Date()

获得指定时间

let date = new Date(2020-1-1)

综合

因为时间对象返回的数据我们不能直接使用,所以需要转换为实际开发中常用的格式

image.png

let date = new Date()

        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let nowDate = date.getDate()
        let hours = date.getHours()
        let minutes = date.getMinutes()
        let second = date.getSeconds()
        let day = date.getDay()
        console.log(`当前时间是${year}-${month}-${nowDate} ${hours}:${minutes}:${second}`);
        console.log(`星期${day}`);

时间戳

时间戳是指1970年01月01日00时00分00秒起至现在的毫秒数,它是一种特殊的计量时间的方式

三种获取时间戳的方法

let date = new Date()
console.log(date.getTime());
console.log(+new Date());
console.log(Date.now());

高考倒计时案例

  let box = document.querySelector('.box')

        setInterval(function() {
            let date = +new Date('2022-6-7 09:00:00')
            let nowDate = Date.now()
            let value = date - nowDate
            let second = parseInt(value / 1000)

            let s = parseInt(second % 60)
            let m = parseInt(second / 60 % 60)
            let h = parseInt(second / 60 / 60 % 24)
            let d = parseInt(second / 60 / 24 / 24)

            s = s > 9 ? s : '0' + s
            m = m > 9 ? m : '0' + m
            h = h > 9 ? h : '0' + h

            box.innerText = `距离2022年高考还剩${d}${h}小时${m}${s}秒`
        }, 1000)