Date 物件用於處理日期與時間。建立方式為:
var myDate = new Date();
值得注意的是,Date 物件會自動把當下的日期與時間存成它的初始值,因此不需要傳入任何參數就能拿到「現在」。
透過 Date 的各種 get 方法取出年、月、日、時、分、秒,再搭配 setInterval 每秒更新一次,就是一個最典型的即時時鐘。
<html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8">
<script type="text/javascript">
function sysTime() {
var now = new Date(); // 建立 Date 物件
var year = now.getFullYear(); // 年份
var month = now.getMonth() + 1; // 月份(注意要 +1)
var date = now.getDate(); // 日
var day = now.getDay(); // 星期
var hour = now.getHours(); // 小時
var minutes = now.getMinutes(); // 分
var sec = now.getSeconds(); // 秒
var arr_week = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
var week = arr_week[day];
var time = year + "年" + month + "月" + date + "日" + week + " " + hour + ":" + minutes + ":" + sec;
document.getElementById("clock").innerHTML = "當前系統時間:" + time;
}
window.onload = function () {
// 每隔 1000 毫秒呼叫一次 sysTime()
window.setInterval("sysTime()", 1000);
};
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
這裡有個一定要記住的陷阱:getMonth() 回傳的是 0 到 11,也就是說 0 代表一月。因此要顯示人類看得懂的月份時,必須 +1;反過來說,若要當成陣列索引使用,則反而不該加 1。
由於月份與星期都是以數字形式回傳,若想顯示名稱,最簡單的做法就是建立一個對照陣列:
<script type="text/javascript">
var d = new Date();
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
document.write("The month is " + month[d.getMonth()]);
</script>
這裡直接用 getMonth() 的回傳值當索引,因為陣列本身就是從 0 開始,剛好對應。
| 方法 | 說明 |
|---|---|
| Date() | 回傳當日的日期與時間 |
| getDate() | 回傳一個月中的第幾天(1~31) |
| getDay() | 回傳一週中的第幾天(0~6,0 為星期日) |
| getMonth() | 回傳月份(0~11) |
| getFullYear() | 以四位數字回傳年份 |
| getHours() | 回傳小時(0~23) |
| getMinutes() | 回傳分鐘(0~59) |
| getSeconds() | 回傳秒數(0~59) |
| getMilliseconds() | 回傳毫秒(0~999) |
除了這些 get 系列,Date 物件也對應提供了 set 系列方法用來設定各項數值,以及 toLocaleString()、toISOString() 等格式化輸出方法,實作時可依需求選用。