15.时间对象

116 阅读2分钟

1.声明时间对象

  • 语法:var timer = new Date()
    • 不传参时timer的输出结果为当前的中国标准时间
  • 语法:var timer = new Date(2023,1,4,21,52,50)
    • 当参数为数字时timer的输出结果会按照参数的顺序依次为年,月,日,时,分,秒进行改变
    • 注意:参数为数字时设置月份时0-11代表1-12月
  • 语法:var timer = new Date('2023-1-4 21:52:50')
    • 当参数为字符串时timer的输出结果会将字符串中-连接的值依次为年,月,日改变,将:连接的值依次为时,分,秒进行改变,日期和时间以空格分割

2.获取时间对象

  • getFullYear
    • 语法:变量.getFullYear()
    • 作用:获取年份
    • 返回值:获取的年份
  • getMonth
    • 语法:变量.getMonthr()
    • 作用:获取月份
    • 返回值:获取的月份
  • getDate
    • 语法:变量.getDate()
    • 作用:获取日
    • 返回值:获取的日
  • getDay
    • 语法:变量.getDay()
    • 作用:获取周几
    • 返回值:获取的周几
  • getHours
    • 语法:变量.getHours()
    • 作用:获取小时
    • 返回值:获取的小时
  • getMinutes
    • 语法:变量.getMinutes()
    • 作用:获取分钟
    • 返回值:获取的分钟
  • getSeconds
    • 语法:变量.getSeconds()
    • 作用:获取秒数
    • 返回值:获取的秒数
  • getMilliseconds
    • 语法:变量.getMilliseconds()
    • 作用:获取毫秒数
    • 返回值:获取的毫秒数
  • getTime
    • 语法:变量.getTimes()
    • 作用:获取从该时间到 1970 年的总毫秒数
    • 返回值:获取的毫秒数

3.设置时间对象

  • setFullYear
    • 语法:变量.setFullYear()
    • 作用:设置年份
  • setMonth
    • 语法:变量.setMonthr()
    • 作用:设置月份
  • setDate
    • 语法:变量.setDate()
    • 作用:设置日
  • setHours
    • 语法:变量.setHours()
    • 作用:设置小时
  • setMinutes
    • 语法:变量.setMinutes()
    • 作用:设置分钟
  • setSeconds
    • 语法:变量.setSeconds()
    • 作用:设置秒数
  • setMilliseconds
    • 语法:变量.setMilliseconds()
    • 作用:设置毫秒数
  • setTime
    • 语法:变量.setTimes()
    • 作用:设置从该时间到 1970 年的总毫秒数