api - 时间对象、时间戳

260 阅读1分钟

获取时间对象

    // new Date()可以获取当前日期对象,包括 年月日时分秒
    let date = new Date()
    console.log(date) // Thu Jan 20 2022 15:16:55 GMT+0800 (中国标准时间)

时间对象年月日时分秒获取

      // getFullYear():获取年
      let year = date.getFullYear()
      
      // getMonth():获取月,0 - 11    //默认是0-11,为了1-12,需要+1
      let month = date.getMonth() + 1
      
      // getDate():获取日
      let day = date.getDate()
      
      // getDay() 获取星期几        //也是0-6,星期天是每周的开始
      let week = date.getDay()
      
      // getHours():获取时
      let hour = date.getHours()
      
      // getMinutes():获取分
      let minute = date.getMinutes()
      
      // getSeconds():获取秒
      let second = date.getSeconds()

时间戳

    // 时间戳:当前指定日期离 1970-1-1 0:0:0 的毫秒值
    
    三种获取方法:
    console.log(date.getTime())

    console.log(+new Date());

    console.log(Date.now());
    
    时间戳的含义是:当前时间与1970-1-1 0:0:0 的时间差,以毫秒级别来显示