【JavaScript】Date 日期对象

56 阅读1分钟

日期对象

实例化

  // 1. 实例化
  // const date = new Date(); // 系统默认时间
  const date = new Date('2023-11-21') // 指定时间
  // date 变量即所谓的时间对象
  console.log(typeof date)

方法

   // 1. 实例化
  const date = new Date();
  // 2. 调用时间对象方法
  // 通过方法分别获取年、月、日,时、分、秒
  const year = date.getFullYear(); // 四位年份
  const month = date.getMonth(); // 0 ~ 11

getFullYear 获取四位年份

getMonth 获取月份,取值为 0 ~ 11

getDate 获取月份中的每一天,不同月份取值也不相同

getDay 获取星期,取值为 0 ~ 6

getHours 获取小时,取值为 0 ~ 23

getMinutes 获取分钟,取值为 0 ~ 59

getSeconds 获取秒,取值为 0 ~ 59

时间戳

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

// 1. 实例化
const date = new Date()
console.log(+date, Date.now(), date.getTime()); //获取当前时间时间戳
  
  
//获取指定日期的时间戳
const date1 = new Date('2033-09-10')
console.log(+date1, Date.parse('2033-09-10'), date1.getTime()); //获取指定时间时间戳