十五、时间对象

39 阅读2分钟

一、时间对象的创建

  1. 不传递时间参数创建
  • 语法:var timer = new Date()
var timer = new Date()
console.log(timer)      //默认获取到本地时间
  1. 传递时间参数创建
  • 传递的参数为数字:
      • 注意:传递数字的时候,最少要传递两个值:年、月;需要特别注意的是,在JS中,0 ~ 11代表1 ~ 12月份
var timer1 = new Date(2020,00)
console.log(timer1)      //此时表示传递2020年1月
var timer2 = new Date(2020,00,12,23,3415)
console.log(timer2)      //此时表示传递2020年1月12日23时34分15秒
  • 传递的参数为字符串:
      • 注意:传递字符串的时候,传递的月份是从1开始
var timer1 = new Date(‘2019’)
console.log(timer1)      //此时表示传递2019年
var timer2 = new Date(‘2020-00-12-23-34-15’)
console.log(timer2)      //此时表示传递2020年1月12日23时34分15秒

二、获取时间对象

以下代码的初始时间均定为:

var timer = new Date()
  1. 得到时间对象中的年份
  • 语法:时间.getFullYear()
var year = timer.getFullYear()
console.log(year)   
  1. 得到时间对象中的月份
  • 语法:时间.getMonth()
var month = timer.getMonth()
console.log(month)
  1. 得到时间对象中的哪一天
  • 语法:时间.getDate()
var date = timer.getDate()
console.log(date)

4.得到时间对象中的小时

  • 语法:时间.getHours()
var hours = timer.getHours()
console.log(hours)

5.得到时间对象中的分钟

  • 语法:时间.Minutes()
var minutes = timer.getMinutes()
console.log(minutes)

6.得到时间对象中的秒钟

  • 语法:时间.getSeconds()
var seconds = timer.getSeconds()
console.log(seconds)

7.得到时间对象中一周的第几天(用0~6表示周日到周六)

  • 语法:时间.getDay()
var days = timer.getDay()
console.log(days) 

8.按照格林威治时间计算从1970年1月1日0时0分0秒到现在(指定日期)的毫秒数

  • 语法:时间.getTime()
var time = timer.getTime()
console.log(time) 

三、设置时间对象

  1. 设置 年
  • 语法:时间.setFullYear()
timer.setFullYear(2018)
console.log(timer.getFullYear())
  1. 设置 月
  • 语法:时间.setMonth()
    • -z
timer.setMonth(11)
console.log(timer.getMonth())
  1. 设置当月的第几天
  • 语法:时间.setDate()
timer.setDate(20)
console.log(timer.getDate())

注意:没有设置本周的第几天

4.设置 时

  • 语法:时间.setHours()
timer.setHours(20)
console.log(timer.getHours())

5.设置 分

  • 语法:时间.setMinutes()
timer.setMinutes(30)
console.log(timer.getMinutes())

6.设置 秒

  • 语法:时间.setSeconds()
timer.setSeconds(40)
console.log(timer.getSeconds())

7.设置 毫秒

  • 语法:时间.setMilliseconds()
timer.setMilliseconds(888)
console.log(timer.getMilliseconds())

8.直接设置到1970的总毫秒

  • 语法:时间.setTime()
timer.setTime(123456789)
console.log(timer.getTime)