JS的时间对象

103 阅读2分钟

61、创建时间对象

JsDate 给我们提供了操作时间的一些方法,是JS内置的一个对象    
    var timer = new Date() 
    //new Date()  会给我们返回一个时间对象
    console.log(timer)
    //Wed Jan 04 2023 14:12:56 GMT+0800 (中国标准时间)

62、时间对象的参数

* 创建时间对象的时候,可以选择传递参数,也可以不传递参数
 *    如果需要传递参数,分为两种方式
①.数字
 * 最少要传递两个值,年 和 月(JS中0-11代表了1-12月)
 ```js
     //                    年   月  日  时   分  秒
     var timer = new Date(2020, 00, 31, 23, 59, 59)
     console.log(timer)
 ```
②.字符串
 * 最少只需要传递一个参数年份即可(字符串的形式传递时月份从1开始)
 ```js
     //                    年   月 日  时 分 秒
     var timer = new Date('2019-02-13 13:14:15')
     console.log(timer)
 ```

63、获取时间对象

    var timer = new Date()
    // console.log(timer)
①.得到时间对象中的年份
    var year = timer.getFullYear()
    console.log(year) //2023
②.得到时间对象中的月份
    var month = timer.getMonth()
    console.log(month) //0 -> 1月
③.得到时间对象中的那一天/日
    var day = timer.getDate()
    console.log(day) //4
④.得到时间对象中的小时
    var hours = timer.getHours()
    console.log(hours) //14
⑤.得到时间对象中的分钟
    var minutes = timer.getMinutes()
    console.log(minutes) //43
⑥.得到时间对象中的秒
    var seconds  = timer.getSeconds()
    console.log(seconds) //44
⑦.得到时间对象中的一周的第几天(用0-6表示周一到周日,但是周日为0)
    var days = timer.getDay()
    console.log(days)
⑧.getTime 按照格林威治时间计算 从1970年1月1日0时0分0秒 到 现在(或指定日期)的毫秒数
    var getTime = timer.getTime()
    console.log(getTime)

64、设置时间对象

    var timer = new Date() 
    //Wed Jan 04 2023 15:04:17 GMT+0800 (中国标准时间)
①设置 年
    timer.setFullYear(2008)
    console.log(timer.getFullYear()) //2008
②设置 月
    timer.setMonth(11)
    console.log(timer.getMonth()) //11
③设置 当月的第几天
    timer.setDate(20)
    console.log(timer.getDate()) //20
⑤注意:没有设置 本周的第几天
⑥设置 时
    timer.setHours(16)
    console.log(timer.getHours()) //16
⑦设置分
    timer.setMinutes(30)
    console.log(timer.getMinutes()) //30
⑧设置秒
    timer.setSeconds(40)
    console.log(timer.getSeconds()) //40
⑨设置毫秒(0-999)
    timer.setMilliseconds(888)
    console.log(timer.getMilliseconds()) //888
⑩直接设置到1970 的总毫秒
    timer.setTime(123456789)
    console.log(timer.getTime()) //123456789