时间对象
定义:
在Js中 Date 给我们提供了操作时间的一些方法,是了js内置的一个对象
时间对象的参数
- 传递参数,分为两种形式
-
1.数字 最少传递两个值,年 和 月(JS中0-11代表了1-12月)
-
2.字符串 最少需要传递一个参数年份即可(字符串的形式传递时月份从 1 开始)
-
3.创建时间对象的时候,可以选择传递参数,也可以不传递参数
// 数字传参 var timer1 = new Date(2020, 00, 31, 23, 59, 59) // ->最少传两个值,月份从 00 开始表示1月 // 年 月 日 时 分 秒 console.log(timer1) // 字符串传参 var timer3 = new Date('2019-02-13 14:25:15') // ->最少传一个值 console.log(timer3) // 不传参 var timer = new Date() console.log(timer) // Wed Jan 04 2023 14:13:47 GMT+0800 (中国标准时间) 当前时间
-
获取时间对象
var timer = new Date()
-
1.得到时间对象中的 年份
var year = timer.getFullYear() console.log(year) -
2.得到时间对象中的 月份 (0-11表示1-12月)
var month = timer.getMonth() console.log(month) -
3.得到时间对象中的 某一天
var day = timer.getDate() console.log(day) -
4.得到时间对象中的 小时
var hours = timer.getHours() console.log(hours) -
5.得到时间对象中的 分钟
var minutes = timer.getMinutes() console.log(minutes) -
6.得到时间对象中的 秒数 (0-59表示1~60秒)
var seconds = timer.getSeconds() console.log(seconds) -
7.得到时间对象中的 一周的第几天 (用0~6表示周日到周六)
var days = timer.getDay() console.log(days) -
8.getTime 按照格林威治时间计算从 1970年1月1日0时0分0秒 到 现在 或 指定日期 -> 计算的是毫秒
var getTimers = timer.getTime() console.log(getTimers)
设置时间对象
var timer = new Date()
-
1.设置 年
timer.setFullYear(2008) console.log(timer.getFullYear()) -
2.设置 月
timer.setMonth(0) console.log( timer.getMonth()) -
3.设置 当月的第几天 ->注意:没有设置本周的第几天
timer.setDate(11) console.log(timer.getDate()) -
4.设置 小时
timer.setHours(18) console.log(timer.getHours()) -
5.设置 分钟
timer.setMinutes(30) console.log(timer.getMinutes()) -
6.设置 秒
timer.setSeconds(22) console.log(timer.getSeconds()) -
7.设置 毫秒
timer.setMilliseconds(888) // 毫秒设置区间0~999 console.log(timer.getMilliseconds()) -
8.直接设置到1970的总毫秒
timer.setTime(123456789) console.log(timer.getTime())