05-时间对象

132 阅读1分钟

实例化

在代码中发现了new关键字时,一般将这个操作称为实例化

  • 获得当前时间

    • let date = new Date()
      
  • 获得指定时间

    • let date = new Date('1949-10-01 18:30:00')
      
    <script>
        let date = new Date()
        document.write(date)
    </script>

时间对象方法

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

方法作用说明
getFullYear()获得年份获取四位年份
getMonth()获得月份取值为 0 ~ 11
getDate()获取月份中的每一天不同月份取值也不相同
getDay()获取星期取值为 0 ~ 6
getHours()获取小时取值为 0 ~ 23
getMinutes()获取分钟取值为 0 ~ 59
getSeconds()获取秒取值为 0 ~ 59
let date = new Date()
document.write(date.getMonth() + 1 )  //月份只能显示0-11 ,在后面+1即可显示正确月份

YYYY-MM-DD HH:mm 形式显示在页面

<div></div>
    <script>    
        let arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
        let div = document.querySelector('div')
        // 页面打开时会有1秒空白,先调用函数就可以解决
        getTime()
        setInterval(getTime,1000)
        
        function getTime(){
        let date = new Date()
        let n = date.getFullYear()
        let y = date.getMonth() +1
        let r = date.getDay()
        let s = date.getHours()
        let f = date.getMinutes()
        let m = date.getSeconds()
        let z = date.getDay()
        div.innerHTML = `今天是:${n}${y}${r}${s}:${f}:${m} ${arr[z]}`
        }
    </script>

时间戳

  • 什么是时间戳

    • 指1970年01月01日00时00分00秒起至现在的毫秒数,它是一种特殊的计量时间的方式
    • 时间戳是总的毫秒数 是独一无二的
    • 计算倒计时:核心思想
    • 将来时间9.1 12:00 有一个时间戳 2000000
    • 现在的时间 8.29 15:00 有一个时间戳1000000
    • 利用将来的时间戳 减去 现在的时间戳 就是剩余的时间毫秒数
    • 转换为时分秒就是剩余的时间了
    • 通过时间戳得到是毫秒
  • 三种方式获得时间戳

    • 第一种:使用getTime()

      • //实例化
        let date = new Date()
        //获取时间戳
        console.log(date.getTime())
        
    • 第二种:简写 +new Date() ★

      • console.log(+new Date())
        
    • 第三种:使用 Date.now()

      • console.log(Date.now())
        
      • 无需实例化

      • 但是只能得到当前的时间戳,前面两种可以返回指定时间的时间戳

    •         console.log(+new Date())  //当前时间戳
              console.log(+new Date('2022-12-01 12:00:00'))  //指定时间戳
      
  • 时间转换公式:

    • 1秒 = 1000毫秒

    • d = parseInt(总秒数/ 60/60 /24); // 计算天数

    • h = parseInt(总秒数/ 60/60 %24) // 计算小时

    • m = parseInt(总秒数 /60 %60 ); // 计算分数

    • s = parseInt(总秒数%60); // 计算当前秒数

倒计时案例

<script>
        let body = document.querySelector('body')
        djs()
        setInterval(djs,1000)
        function djs(){
        // 现在时间戳
        let now = +new Date()
        // 指定时间戳
        let last = +new Date('2022-12-1')
        // 计算剩余毫秒数
        let count = (last - now) /1000
        let d = parseInt(count /60 /60 /24);    // 计算天数
        d = d <10 ? '0' + d : d  //如果数字小于10 就在数字前面加0,否则就输出原数值
        let h = parseInt(count /60 /60 %24)   // 计算小时
         h = h < 10 ? '0' + h : h  //如果数字小于10 就在数字前面加0,否则就输出原数值
        let m = parseInt(count /60 %60 );   // 计算分数
        m = m <10 ? '0' + m : m  //如果数字小于10 就在数字前面加0,否则就输出原数值
        let s = parseInt(count %60);   // 计算当前秒数
        s = s < 10 ? '0' + s : s   //如果数字小于10 就在数字前面加0,否则就输出原数值
        body.innerHTML = `距离12月1日还有: ${d}${h}${m}${s} 秒`
        }
</script>