Date and time
內建的物件 Date,可以創造、改變、計算時間。
Creation
new Date()
let now = new Date(); alert( now ); // shows current date/timenew Date(milliseconds)
// 0 means 01.01.1970 UTC+0 let Jan01_1970 = new Date(0); alert( Jan01_1970 ); // now add 24 hours, get 02.01.1970 UTC+0 let Jan02_1970 = new Date(24 * 3600 * 1000); alert( Jan02_1970 );new Date(datestring)
// string 用 Date.parse 轉換成時間 let date = new Date("2017-01-26"); alert(date);new Date(year, month, date, hours, minutes, seconds, ms)
The
yearmust have 4 digits:2013is okay,98is not.The
monthcount starts with0(Jan), up to11(Dec).The
dateparameter is actually the day of month, if absent then1is assumed.If
hours/minutes/seconds/msis absent, they are assumed to be equal0.new Date(2011, 0, 1, 0, 0, 0, 0); // // 1 Jan 2011, 00:00:00 new Date(2011, 0, 1); // the same, hours etc are 0 by default let date = new Date(2011, 0, 1, 2, 3, 4, 567); alert( date ); // 1.01.2011, 02:03:04.567
Access date components
getFullYear() 取得年份
getMonth() 取得月份 0 - 11
getDate() 取得日期 1 - 31
getHours(), getMinutes(), getSeconds(), getMilliseconds() 取得對應的時間
getDay() 取得星期 0 (sunday) - 6 (saturday)
以上方法都是返回當地時間, getUTCFullYear(), getUTCMonth(), getUTCDay() 得到 UTC+0 時間
getTime() 從 1970-1-1 00:00:00 UTC+0 開始的 milliseconds
getTimezoneOffset() 返回跟 UTC+0 的時間差(分鐘)
setFullYear(year [, month, date])
setMonth(month [, date])
setDate(date)
setHours(hour [, min, sec, ms])
setMinutes(min [, sec, ms])
setSeconds(sec [, ms])
setMilliseconds(ms)
setTime(milliseconds) (sets the whole date by milliseconds since 01.01.1970 UTC)
除了 setTime() 都有 UTC+0 的時間。
Autocorrection
Date to number, date diff
Date.now()
Benchmarking
Date.parse from a string
YYYY-MM-DD– is the date: year-month-day.The character
"T"is used as the delimiter.HH:mm:ss.sss– is the time: hours, minutes, seconds and milliseconds.The optional
'Z'part denotes the time zone in the format+-hh:mm. A single letterZthat would mean UTC+0.
Last updated
Was this helpful?