日期对象

48 阅读1分钟

实例化

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

  • 创建一个时间对象并获取时间
    • 获得当前时间:const date = new Date()
    • 获得指定时间:const date = new Date('2023-1-1')

日期对象方法

image.png

获取当前时间函数

 // 获取当前时间
const date = new Date()
function getTime () {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  let dateTime = `${year}${month}${day} ${hour}:${minute}:${second}`
  console.log(dateTime)
}

时间戳

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

  • 算法:
  • 将来的时间戳 - 现在的时间戳 = 剩余时间毫秒数
  • 剩余时间毫秒数 转换为 剩余时间的 年月日时分秒 就是 倒计时时间
  • 比如 将来时间戳 2000ms - 现在时间戳 1000ms = 1000ms
  • 1000ms 转换为就是 0小时0分1秒

1. getTime()

const date = new Date()
console.log(date.getTime())

3. +new Date()

console.log(+new Date())

5. Date.now()

无需实例化

但是只能得到当前的时间戳,而前面两种可以反悔指定时间的时间戳

console.log(Date.now())