Date對象:用于處理時間和日期。
創建方法:var myDate = new Date()
Data對象會自動把當前時間與日期保存為初始值。
document.write(Date())
返回結果:
Tue Mar 13 2018 20:11:03 GMT+0800(中國標準時間)
Date對象的方法:
- Date(): 返回當前的日期和時間
- getDate() 返回今天的日(今天是本月的第幾天?)
var day = new Date()
document.write(day.getDate())
返回結果:2 (今天確實是2號)
- getMonth() 返回本月的月份 返回值是 0(一月) 到 11(十二月) 之間的一個整數
var day = new Date()
document.write(day.getMonth())
返回結果:3
正確月份操作:
var day = new Date()
document.write(day.getMonth()+1)
- getFullYear() 返回年份
var day = new Date()
document.write(day.getFullYear())
返回結果:2018
- getDay() 返回今天是星期幾
var day = new Date()
document.write(day.getDay())
返回結果:1
- getHours() 獲取當前多少時。
var day = new Date()
document.write(day.getHours())
返回結果:20 (截取測試時間20:22)
- getMinutes() 獲取當前分鐘數
var day = new Date()
document.write(day.getMinutes())
返回結果:22 (截取測試時間20:22)
- getSeconds() 獲取秒數
var day = new Date()
document.write(day.getSeconds())
返回結果:12
- getMilliseconds() 獲取毫秒數
var day = new Date()
document.write(day.getMilliseconds())
- setDate() 改變當月中的日
改前: Tue Mar 13 2018 20:00:19 GMT+0800 (中國標準時間)
var day = new Date()
day.setDate(1) //括號內填寫需要更改的日期
document.write(day)
//改后: Thu Mar 01 2018 20:03:06 GMT+0800 (中國標準時間)
- 同理可得
SetFullYear()改變年份
SetMonth() 改變月份
SetHours() 改變時
Setminutes() 改變分
Setseconds() 改變秒
SetMilliseconds()改變毫秒